#!/usr/bin/env python
import psycopg2
import sys
import datetime

sys.path.append('../../')
sys.path.append('../')
from django.core.management import setup_environ
from globalhome import settings
setup_environ(settings)
from settings import DATABASES

conn = psycopg2.connect("dbname='%(NAME)s' user='%(USER)s' host='%(HOST)s' password='%(PASSWORD)s'" % DATABASES['default'])
cur = conn.cursor()
cur.connection.set_isolation_level(1)
cur.connection.commit()

try:
    cur.execute("DELETE from fin_docs_signeds_m2m_data_centr_zakazy")
except Exception, e:
    print e
    cur.connection.rollback()
else:
    cur.connection.commit()

try:
    cur.execute("SELECT setval('fin_docs_signeds_m2m_data_centr_zakazy_id_seq', 1, False);")
except Exception, e:
    print e
    cur.connection.rollback()
else:
    cur.connection.commit()
try:
    cur.execute("SELECT * FROM fin_docs_signeds WHERE zakaz_id != 0 ORDER by id")
    fin_doc_signeds = cur.fetchall()
    for fin_doc in fin_doc_signeds:
        print "------------------------------------------------------------------------------"
        print "-------------------- start add record for id=%s --------------------"%fin_doc[0]
        cur.execute("INSERT INTO fin_docs_signeds_m2m_data_centr_zakazy(fin_doc_id, zakaz_id) VALUES (%s, %s)", (fin_doc[0],fin_doc[7],))
        print "--------------------- end add_record for id=%s ---------------------"%fin_doc[0]
        print "------------------------------------------------------------------------------"
except Exception, e:
    print e
    cur.connection.rollback()
else:
    cur.connection.commit()
print "Add records in fin_docs_signeds_m2m_data_centr_zakazy is successfully complete"
