#!/usr/bin/env python

import psycopg2, uuid, datetime, time

bdd_main  = "dbname='alloa' user='mad' host='192.168.0.67' password='mad8888'"
bdd_local = "dbname='alloa2' user='dev' host='127.0.0.1' password='dev8888'"

db  = psycopg2.connect(bdd_main)
cur = db.cursor()

newdb  = psycopg2.connect(bdd_local)
newcur = newdb.cursor()

sql = "SELECT frlibtour, gblibtour, frdesctour, gbdesctour, etapes, fraccroche, gbaccroche FROM production.tour"
cur.execute(sql)

for row in cur.fetchall():
	if row[4] == "None" or not row[4]:
		continue

	uuidpack = str(uuid.uuid4())


	sql = "INSERT INTO pack.pack (uuidpack, e_datecreation, e_datemodification, arevoirle, encourstraitement, z_statutsuivi, z_groupedesuivi, z_cumultemps, z_esvn, is_publique, frlibpack, gblibpack, frdescpack, gbdescpack, fraccroche, gbaccroche) VALUES ('{uuidpack}', '{e_datecreation}', '{e_datemodification}', '{arevoirle}', {encourstraitement}, {z_statutsuivi}, '{z_groupedesuivi}', {z_cumultemps}, {z_esvn}, {is_publique}, '{frlibpack}', '{gblibpack}', '{frdescpack}', '{gbdescpack}', '{fraccroche}', '{gbaccroche}')".format(uuidpack=uuidpack, e_datecreation=str(datetime.datetime.now()), e_datemodification=str(datetime.datetime.now()), arevoirle='2016-10-29', encourstraitement=False, z_statutsuivi=0, z_groupedesuivi='ALLOA', z_cumultemps=0, z_esvn="''", is_publique=False, frlibpack=row[0], gblibpack=row[1], frdescpack=row[2].replace("'", "''"), gbdescpack=row[3].replace("'", "''"), fraccroche=row[5].replace("'", "''"), gbaccroche=row[6].replace("'", "''"))

	try:
		newcur.execute(sql)
		newdb.commit()
	except:
		continue

	for x in row[4].split('|'):
		if x == "":
			continue

		etape = x.split(';')
		if etape[0] == "":
			continue

		sql = "INSERT INTO pack.etape (uuidetape, ordre, uuidville, uuidpack) VALUES ('{}', {}, '{}', '{}')".format(str(uuid.uuid4()), etape[2], etape[0], uuidpack)

		try:
			newcur.execute(sql)
			newdb.commit()
		except:
			pass


