#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import os

GENERATE_SQL_DIR = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 
        "generated_files")

def volcar_a_fichero(countries, file_name):
    """
    Recorre la lista de cadenas recibida y las vuelca en un fichero de texto.
    """
    abs_file_name = os.path.join(GENERATE_SQL_DIR, file_name)
    print("Volcando a %s..." % abs_file_name)
    inserts = open(abs_file_name, "w")
    inserts.write(countries)
    inserts.close()

def main():
    dic_countries, dic_provinces, dic_towns, dic_cps = parse_fichero_csv()
    inserts_countries = create_countries(dic_countries)
    inserts_provinces = create_provinces(dic_provinces)
    inserts_towns = create_towns(dic_towns)
    inserts_cps = create_cps(dic_cps)
    volcar_a_fichero(inserts_countries, "countries.txt")
    volcar_a_fichero(inserts_provinces, "provinces.txt")
    volcar_a_fichero(inserts_towns, "towns.txt")
    volcar_a_fichero(inserts_cps, "cps.txt")

def parse_fichero_csv():
  # Read the first csv with the contries
  csvfile = open(os.path.join("CSV" , "country.csv"), "r")
  reader = csv.reader(csvfile)

  countries = {}
  counter = 1  
  for row in reader:
    countries[row[1]] = counter
    counter += 1
  csvfile.close()

  #Open the CSV file with all the information
  csvfile = open(os.path.join("CSV", "postal_codes.csv"), "r")
  reader = csv.reader(csvfile)
  #Create the dictionaries
  provinces = {}
  towns = {}
  cps = {}

  #Loop the file creating the dictionaries
  province_counter = 1
  towns_counter = 1
  cp_counter = 1
  for row in reader:
    cp = row[0]
    town = row[2]
    province = row[3]
    if province not in provinces:
        provinces[province] = {"id": province_counter, 
                               "country": countries["España"]}
        province_counter += 1
    if town not in towns:
        towns[town] = {"id": towns_counter, "province": provinces[province]["id"]}
        towns_counter += 1
    cps[cp] = {"id": cp_counter, "town": towns[town]["id"]}
    cp_counter += 1

  csvfile.close()

  return countries, provinces, towns, cps

def create_countries(dic_countries):

    countries_array = ""
    countries_array = countries_array + "$countries = array(\n"
    for country_key in list(dic_countries.keys()):
        countries_array = countries_array + "array('name' => '{0}', 'id' => '{1:03d}'),\n".format(
            country_key,
            dic_countries[country_key])
    countries_array = countries_array + ");"
    return countries_array


def create_provinces(dic_provinces):
    
    provinces_array = ""
    provinces_array = provinces_array + "$provinces = array(\n"
    for province_key in list(dic_provinces.keys()):
        provinces_array = provinces_array + "array('name' => '{0}', 'id' => '{1:03d}', 'country' => '{2:03d}'),\n".format(
                    province_key, 
                    dic_provinces[province_key]["id"],
                    dic_provinces[province_key]["country"])
    provinces_array = provinces_array + ");"
    return provinces_array
    
def create_towns(dic_towns):
    towns_array = ""
    towns_array = towns_array + "$provinces = array(\n"
    for town_key in list(dic_towns.keys()):
        towns_array = towns_array + "array('name' => \"{0}\", 'id' => '{1:03d}', 'province' => '{2:03d}'),\n".format(
            town_key, 
            dic_towns[town_key]["id"], 
            dic_towns[town_key]["province"])
    towns_array = towns_array + ");"
    return towns_array

def create_cps(dic_cps):
    cps_array = ""
    cps_array = cps_array + "$cps = array(\n"
    for cp_key in list(dic_cps.keys()):
        cps_array = cps_array + "array('codpostal' => '{0}', 'id' => '{1:03d}', 'town' => '{2:03d}'),\n".format(
                cp_key,
                dic_cps[cp_key]["id"],
                dic_cps[cp_key]["town"])

    cps_array = cps_array + ");"
    return cps_array

#At the end of the file
if __name__ == "__main__":
    main()

