#!/usr/bin/env python


import sys
import os
import json
import shutil
import subprocess
import json
import pprint
import time
import datetime
import base64
import MySQLdb
import MySQLdb.cursors

sys.path.insert(1, os.path.join(sys.path[0], '..'))

from common.buildmonitor_db import do_query, get_value_from_query_data, do_many_query
from common.buildmonitor_extention import BuildMonitorExtention



def unicode_to_str(obj):
    """convert unicode object to str"""

    if isinstance(obj, list):
        return [unicode_to_str(element) for element in obj]
    elif isinstance(obj, dict):
        return {unicode_to_str(key) : unicode_to_str(value) for key, value \
                in obj.iteritems()}
    elif isinstance(obj, unicode):
        return obj.encode('utf-8')
    else:
        return obj


class TOOLS_DB(BuildMonitorExtention):

    def __init__(self):
        BuildMonitorExtention.__init__(self)

    def jira_update(self, table, value):
        """write DB // tool_jira_issues table"""


        for item in value:

            try:

                for k, v in item.items():
                    if type(v) == str:
                        item[k] = v.replace("'", '"')
                        item[k] = item[k].rstrip('\\')
                        #print "[INFO] item[k] : ", k ,  item[k]


                #print item_data
                columns_string = "(`" + "`,`".join(item.keys())+"`)"
                values_string  = "','".join(map(str, item.values()))

                query = "SELECT id FROM %s WHERE jira_key = "% (table, ) +"%s"
                query_data = (item['jira_key'],)
                jira_key_id = get_value_from_query_data(query, query_data)


                if jira_key_id > 0: #update
                    query = "UPDATE %s SET status = \"%s\" WHERE jira_key = " % (table, item['status']) + "%s"
                    query_data = (item['jira_key'],)
                    do_query(query, query_data)


                else: #insert
                    query = "INSERT INTO %s %s VALUES " % (table, columns_string) + "(%s, %s, %s, %s, %s, %s, %s)"
                    query_data = (item['status'],item['priority'],item['created'],item['jira_key'],item['title'],item['project'],item['assignee'])
                    do_query(query, query_data)



            except MySQLdb.IntegrityError as error:
                #print "[ERROR]", sql
                print ("[ERROR] msg {}".format(error))


    def prereviewtest_update(self, table, value):
        """write DB // tool_jira_issues table"""

        for item in value:

            try:

                for k, v in item.items():
                    if type(v) == str:
                        item[k] = v.replace("'", '"')
                        item[k] = item[k].rstrip('\\')
                        print "[INFO] item[k] : ", k ,  item[k]


                #print item_data
                columns_string = "(`" + "`,`".join(item.keys())+"`)"
                values_string  = "','".join(map(str, item.values()))

                query = "SELECT id FROM %s "% (table, ) +"WHERE commit_id = %s AND test_type = %s"
                query_data = (item['commit_id'],item['test_type'])
                #query = "SELECT id FROM %s "% (table, ) +"WHERE commit_id = %s"
                #query_data = item['commit_id']
                commit_id = get_value_from_query_data(query, query_data)
                print "commit_id : ", commit_id

                if commit_id > 0: #update
                    query = "UPDATE %s SET test_status = \"%s\" WHERE commit_id = " % (table, item['test_status']) + "%s"
                    query_data = (item['commit_id'],)
                    do_query(query, query_data)


                else: #insert
                    query = "INSERT INTO %s %s VALUES " % (table, columns_string) + "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
                    query_data = (item['commit_id'],item['committer'],item['commit_event_type'],item['test_type'],item['gerrit'],\
                    				item['commit_project'],item['test_date'],item['test_status'],item['test_worker_job'],item['commit_branch'])
                    do_query(query, query_data)



            except MySQLdb.IntegrityError as error:
                #print "[ERROR]", sql
                print ("[ERROR] msg {}".format(error))


if __name__ == "__main__":


    tools_db =  TOOLS_DB()

    f = open( 'file0', 'r')
    str1 = subprocess.check_output('pwd')
    RAW = unicode_to_str(json.loads(f.read()))
    f.close()
    print "RAW = %s" % RAW
    #print "RAW.items()= %s" % RAW.items()


    for table, value in RAW.items():
        print table , value
        if "tool_jira_issues" == table:
            tools_db.jira_update(table, value)
        elif "tool_prereviewtest_status" == table:
            tools_db.prereviewtest_update(table, value)

    exit()


