#!/usr/bin/env python
import psycopg2

newbdd          = {}
newbdd['host']  = "192.168.0.67"
newbdd['port']  = "5432"
newbdd['base']  = "alloa"
newbdd['login'] = "mad"
newbdd['mdp']   = "mad8888"

bdd          = {}
bdd['host']  = "127.0.0.1"
bdd['port']  = "5432"
bdd['base']  = "backup"
bdd['login'] = "dev"
bdd['mdp']   = "dev8888"

try:
    db      = psycopg2.connect("dbname='"+ bdd['base'] +"' user='" + bdd['login'] +"' host='" + bdd['host'] +"' password='" + bdd['mdp'] +"'")
    newdb   = psycopg2.connect("dbname='"+ newbdd['base'] +"' user='" + newbdd['login'] +"' host='" + newbdd['host'] +"' password='" + newbdd['mdp'] +"'")
    cur     = db.cursor()
    newcur  = newdb.cursor()
except:
    raise

sql = "SELECT uuidnewsweb, z_date_creation, z_date_modification, z_groupe_createur, z_en_cours_traitement, z_date_a_revoir_le, z_locale_svn, z_historique, frlibnewsweb, gblibnewsweb, frtextnewsweb, gbtextnewsweb, expediteur, signature_expediteur, date_de_lenvoi, is_modele, refnewsweb, uuidimage, is_publique FROM marketing.newsweb"
cur.execute(sql)

for row in list(cur.fetchall()):
	row = list(row)
	if row[10] is None:
		row[10] = ""
	if row[11] is None:
		row[11] = ""
	if row[17] is None:
		row[17] = ""
	if row[14] is None:
		row[14] = "NULL"
	else:
		row[14] = "'{}'".format(row[14])

	sql = "INSERT INTO marketing.newsweb(uuidnewsweb, e_semaphore, e_datecreation, e_datemodification, e_historique, arevoirle, encourstraitement, z_statutsuivi, z_groupedesuivi, z_cumultemps, z_esvn, frlibnewsweb, gblibnewsweb, frtextnewsweb, gbtextnewsweb, expediteur, signature_expediteur, date_de_lenvoi, is_modele, refnewsweb, is_publique, uuidimage) VALUES ('{}', '', '{}', '{}', '{}', '{}', {}, 0, 'ALLOA', 0, 0, '{}', '{}', '{}', '{}', '{}', '{}', {}, {}, '{}', {}, '{}')".format(row[0], row[1], row[2], row[7], row[5], row[4], row[8].replace("'", "''"), row[9].replace("'", "''"), row[10].replace("'", "''"), row[11].replace("'", "''"), row[12], row[13], row[14], row[15], row[16], row[18], row[17])

	try:
		newcur.execute(sql)
		newdb.commit()
	except:
		print(sql)
		raise