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

import os
import sys
import MySQLdb
import MySQLdb.cursors
import xml.etree.ElementTree as ET
import urllib2
import re
import datetime
from codebase import *
from common.buildtrigger import trigger_info, trigger_next

def notify_test_result(MYSQL, build_project_id, status):
    """
    Notify the test results to submitters
    """
    sql_data = (build_project_id,)
    sql = "SELECT ip.project_name FROM info_project ip, build_project bp WHERE ip.id = bp.info_project_id AND bp.id = %s"
    MYSQL['cursor'].execute(sql, sql_data)
    row = MYSQL['cursor'].fetchall()
    if len(row) > 0:
        project_name = row[0]['project_name']
        print project_name
        data = {"project" : project_name,
                "status" : status
               }
        trigger_next("NOTIFY-BUILDSTATUS", data)

def is_test_succeeded(data, is_ref_exist, is_perf_exist):

    # if ref results exist, compare with them.
    if is_ref_exist:
        for suite in data['TCT']['SUITE'].keys():
            #c = 'pass_case'
            #if data['TCT']['SUITE'][suite][c] < data['REF']['SUITE'][suite][c]:
            #    return 0
            case_tests = ['fail_case', 'block_case', 'na_case']
            for c in case_tests:
                if data['TCT']['SUITE'][suite][c] > data['REF']['SUITE'][suite][c]:
                    return 0
    else:
        if data['TCT']['COUNT']['total_case'] != data['TCT']['COUNT']['pass_case']:
            return 0

    # smoke test.
    if data['SMOKES']['COUNT']['fail_case'] > 0:
        return 0

    # perf test
    if (is_perf_exist) and (data['PERFS']['COUNT']['fail_case'] > 0):
        return 0

    return 1

def find_build_project_id(data, snapshot, sr_id):
    snapshot_name = None
    src = re.search(r'.*.([\d]{8}.[\d]{6})', snapshot)
    if src and src.groups() and len(src.groups()) == 1:
        snapshot_name = snapshot
    else:
        try:
            platform_ver = data.get('PERFS').get('DEVICE').get('Platform_ver.')
            snapshot_check = re.search(r'.*.([\d]{8}.[\d]{6})', platform_ver)
            if snapshot_check and snapshot_check.groups() and len(snapshot_check.groups()) == 1:
                snapshot_name = platform_ver
        except AttributeError:
            pass

    build_project_id = 0
    if snapshot_name:
        sql = "SELECT build_project_id FROM build_snapshot " \
              "WHERE snapshot_name=%s ORDER BY id DESC LIMIT 1"
        MYSQL['cursor'].execute(sql, (snapshot_name,))
    else:
        sql_data = (sr_id,)
        sql = "SELECT build_project_id FROM sr_stage " \
              "WHERE sr_status_id=%s AND info_stage_id<=8 " \
              "AND build_project_id!=0 ORDER BY stage_start_time LIMIT 1"

    row = MYSQL['cursor'].fetchall()
    if len(row) > 0:
        build_project_id = row[0]['build_project_id']

    return build_project_id

def insert_test_stage_for_snapshot(data, MYSQL, snapshot, status):
    INFO_STAGE_ID_FOR_SNAPSHOT_TEST = 200

    # Update snapshot test status
    update_sql = "UPDATE build_snapshot " \
                 "SET test_status=%s " \
                 "WHERE snapshot_name=%s "
    MYSQL['cursor'].execute(update_sql, (status, snapshot))
    MYSQL['connection'].commit()

    # Find sr id and build id
    sr_build_list = []
    sql = "SELECT sr_status_id, build_project_id " \
          "FROM sr_stage WHERE build_project_id IN " \
          " (SELECT build_project_id FROM build_snapshot " \
          "  WHERE snapshot_name=%s) " \
          "GROUP BY sr_status_id, build_project_id"
    MYSQL['cursor'].execute(sql, (snapshot,))
    row = MYSQL['cursor'].fetchall()
    if len(row) > 0:
        sr_build_list = [ (x['sr_status_id'], \
                           INFO_STAGE_ID_FOR_SNAPSHOT_TEST, \
                           data['TCT']['start_at'], \
                           data['TCT']['end_at'], \
                           status, \
                           x['build_project_id']) for x in row ]

    if len(sr_build_list) <= 0:
        print('No matching build project ids...')
        return

    print(sr_build_list)

    # Delete old records
    delete_sql = "DELETE FROM sr_stage " \
          "WHERE sr_status_id IN (%s) " \
          "AND build_project_id IN (%s) " \
          "AND info_stage_id=%%s" \
          % (",".join(["{}".format(x[0]) for x in sr_build_list]), \
             ",".join(["{}".format(x[5]) for x in sr_build_list]))
    MYSQL['cursor'].execute(delete_sql, (INFO_STAGE_ID_FOR_SNAPSHOT_TEST,))
    MYSQL['connection'].commit()

    # Insert snapshot test status
    sql = "INSERT INTO sr_stage " \
          "(sr_status_id, info_stage_id, stage_start_time, stage_end_time, " \
          " stage_status, build_project_id)" \
          " VALUES (%s, %s, %s, %s, %s, %s)"
    MYSQL['cursor'].executemany(sql, sr_build_list)
    MYSQL['connection'].commit()

    return

def insert_test_stage(data, MYSQL, sr_id, snapshot, is_ref_exist, is_perf_exist, ordering=None):

    INFO_STAGE_ID_FOR_TEST = 101

    status = 'F'
    if is_test_succeeded(data, is_ref_exist, is_perf_exist):
        status = 'S'

    if sr_id is None:
        print ("No SR ID means SNAPSHOT TEST! {}".format(snapshot))
        return insert_test_stage_for_snapshot(data, MYSQL, snapshot, status)

    build_project_id = find_build_project_id(data, snapshot, sr_id)

    # Handle multi profile results
    total = 1
    current = 1
    if ordering is not None and ordering.get('total', 0) > 1:
        total = ordering.get('total')
        current = ordering.get('current')
    status_detail = ['-'] * total
    o_sql = "SELECT stage_status_detail FROM sr_stage WHERE sr_status_id=%s " \
            " AND build_project_id=%s AND info_stage_id=%s"
    o_sql_data = (sr_id, build_project_id, INFO_STAGE_ID_FOR_TEST)
    MYSQL['cursor'].execute(o_sql, o_sql_data)
    o_row = MYSQL['cursor'].fetchall()
    if len(o_row) > 0:
        o_status = o_row[0].get('stage_status_detail').split(',')
        if len(o_status) == total:
            status_detail = o_status
    status_detail[current - 1] = status
    if '-' in status_detail:
        status = 'W'
    elif 'F' in status_detail:
        status = 'F'

    cur_time = datetime.datetime.now()

    # Delete old records
    delete_sql = "DELETE FROM sr_stage " \
          "WHERE sr_status_id=%s " \
          "AND build_project_id=%s " \
          "AND info_stage_id=%s"
    MYSQL['cursor'].execute(delete_sql, (sr_id, build_project_id, INFO_STAGE_ID_FOR_TEST))
    MYSQL['connection'].commit()

    # Insert snapshot test status
    sql = "INSERT INTO sr_stage " \
          "(sr_status_id, info_stage_id, stage_start_time, stage_end_time, " \
          " stage_status, build_project_id, stage_status_detail)" \
          " VALUES (%s, %s, %s, %s, %s, %s, %s)"
    sql_data = (sr_id, INFO_STAGE_ID_FOR_TEST, cur_time, cur_time, status, build_project_id, \
                ','.join(status_detail))
    pprint.pprint(sql)
    pprint.pprint(sql_data)
    MYSQL['cursor'].execute(sql, sql_data)
    MYSQL['connection'].commit()

    # Add notify status
    notify_test_result(MYSQL, build_project_id, status)

if __name__ == "__main__":

    CONFIG = {
        'FILE'  : {
            'BASE'  : "config.base",
            'MYSQL' : "config.mysql.test",
            'RAW'   : "trbs.txt"
        },

        'BASE'  : {},
        'MYSQL' : {},
        'RAW'   : {}
    }



    print "=====[ TRBS Test Write ]=====\n"

#    For Debug
#    CONFIG['BASE']  = loadJSON( CONFIG['FILE']['BASE'] )
#    CONFIG['MYSQL'] = loadJSON( CONFIG['FILE']['MYSQL'] )


    #pprint.pprint( CONFIG['RAW'] )
    #exit()

    temp = os.getenv('file0')
    if temp:
        paramfile = "file0"
        if not os.path.isfile( paramfile ):
            paramfile = "../file0"
            if not os.path.isfile( paramfile ):
                print "[ERROR] file(%s) was not found!" % paramfile
                exit(1)

        f = open( paramfile, 'r')
        CONFIG['RAW'] = unicode_to_str(json.loads(f.read()))
        f.close()
    else:
        print "[ERROR] TRBS_DATA is empty!"
        exit(1)

    print '[INFO] Jenkins TRBS_DATA loaded'
    pprint.pprint( CONFIG['RAW'] )
    #exit(0)


    #CONFIG['RAW']   = loadJSON( CONFIG['FILE']['RAW'] )

    #pprint.pprint( CONFIG['RAW'] )
    #exit()


    if( not 'BASE' in CONFIG['RAW'].keys() ):
        print "[ERROR] BASE value empty!"
        exit(1)

    DINFO = {
        'sr'           : CONFIG['RAW']['BASE']['sr'],
        'snapshot_num' : CONFIG['RAW']['BASE']['snapshot_num'],
        'tct_profile'  : CONFIG['RAW']['TCT']['environment']['tct_profile']
    }

    print "[INFO] CONFIG : sr =", DINFO['sr'], ", snapshot_num =", DINFO['snapshot_num']





    MYSQL = {}

    # connect mysql
#    if CONFIG['BASE']['MODE'] == "debug":
#        MYSQL['connection'] = MySQLdb.connect( host  =CONFIG['MYSQL']['host'],
#                                               user  =CONFIG['MYSQL']['user'],
#                                               passwd=CONFIG['MYSQL']['password'],
#                                               db    =CONFIG['MYSQL']['database'],
#                                               cursorclass=MySQLdb.cursors.DictCursor)
#        print "[DEBUG] MYSQL : Connect host =", CONFIG['MYSQL']['host'], ", database =", CONFIG['MYSQL']['database']

    MYSQL['connection'] = MySQLdb.connect( host  =os.getenv("BUILDMONITOR_IP"),
                                           user  =os.getenv("BUILDMONITOR_USER"),
                                           passwd=os.getenv("BUILDMONITOR_PASS"),
                                           db    =os.getenv("BUILDMONITOR_NAME"),
                                           cursorclass=MySQLdb.cursors.DictCursor)

    print "[INFO] MYSQL : Connect host =", os.getenv("BUILDMONITOR_IP"), ", database =", os.getenv("BUILDMONITOR_NAME")




    MYSQL['cursor'] = MYSQL['connection'].cursor()



    SQL = {}
    SQL['SR'] = {}
    # select sr
    SQL['SR']['select_srinfo'] = (
        "SELECT * "
        "FROM sr_status s, sr_status_detail d "
        "WHERE s.sr= %(sr)s AND d.sr_status_id = s.id ORDER BY d.id DESC"
    )


    MYSQL['cursor'].execute( SQL['SR']['select_srinfo'], DINFO )
    TEMP = MYSQL['cursor'].fetchall()


    # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
    if len( TEMP ) > 0:
        DINFO['sr_status_id']          = TEMP[0]['sr_status_id']
        DINFO['status']                = TEMP[0]['status']
        DINFO['trbs_build_project_id'] = TEMP[0]['pre_build_project_id']

        print ("[INFO] MYSQL : sr_status_id = '%(sr_status_id)s', trbs_build_project_id = %(trbs_build_project_id)s" % DINFO)

    else:
        print ("[ERROR] MYSQL : Can not search sr_status where sr = %(sr)s" % DINFO)
        DINFO['sr_status_id']          = None
        DINFO['status']                = None
        DINFO['trbs_build_project_id'] = None


    # If reference is exists, then insert into DB.
    isExistRef = True

    if 'environment' not in CONFIG['RAW']['REF'] :
        isExistRef = False

    if ( isExistRef ) :
        SQL['REF'] = {}
        # select ref
        SQL['REF']['select'] = (
            "SELECT * "
            "FROM trbs_ref "
            "WHERE build_id= %(build_id)s AND tct_profile = %(tct_profile)s ORDER BY id DESC"
        )

        MYSQL['cursor'].execute( SQL['REF']['select'], CONFIG['RAW']['REF']['environment'] )
        TEMP = MYSQL['cursor'].fetchall()

        VALUES = {
            'total'         : CONFIG['RAW']['REF']['COUNT']['total_case'],
            'pass'          : CONFIG['RAW']['REF']['COUNT']['pass_case'],
            'fail'          : CONFIG['RAW']['REF']['COUNT']['fail_case'],
            'block'         : CONFIG['RAW']['REF']['COUNT']['block_case'],
            'na'            : CONFIG['RAW']['REF']['COUNT']['na_case'],
            'pcnt'          : round( (float(CONFIG['RAW']['REF']['COUNT']['pass_case'])/float(CONFIG['RAW']['REF']['COUNT']['total_case']))*100, 2 ),
            'plan_name'     : CONFIG['RAW']['REF']['plan_name'],
            'time_start'    : CONFIG['RAW']['REF']['start_at'],
            'time_end'      : CONFIG['RAW']['REF']['end_at'],
            'build_id'      : CONFIG['RAW']['REF']['environment'].get('build_id'),
            'device_id'     : CONFIG['RAW']['REF']['environment'].get('device_id'),
            'device_model'  : CONFIG['RAW']['REF']['environment'].get('device_model'),
            'device_name'   : CONFIG['RAW']['REF']['environment'].get('device_name'),
            'device_host'   : CONFIG['RAW']['REF']['environment'].get('device_host'),
            'manufacturer'  : CONFIG['RAW']['REF']['environment'].get('manufacturer'),
            'tct_profile'   : CONFIG['RAW']['REF']['environment'].get('tct_profile'),
            'tct_version'   : CONFIG['RAW']['REF']['environment'].get('tct_version'),
            'url'           : CONFIG['RAW']['REF']['url']
        }

        table = "trbs_ref"
        sql = ""

        # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
        if len( TEMP ) > 0:
            DINFO['ref_id']          = TEMP[0]['id']
            sql = makeUpdateSQL( table, VALUES, DINFO['ref_id'] )
            print ("[INFO] MYSQL : Can search Reference id = %(id)s, build_id = %(build_id)s" % TEMP[0])
            print "[INFO] MYSQL : Updated Ref to", table, ", build_id =", VALUES['build_id']

        else:
            print "[WARN] MYSQL : There is no Reference TCT result. Now, Inserting...", CONFIG['RAW']['REF']['environment']['build_id']

            sql = makeInsertSQL( table, VALUES )
            print "[INFO] MYSQL : INSERT to", table, ", build_id =", VALUES['build_id']

        try:
            MYSQL['cursor'].execute( sql )
            MYSQL['connection'].commit()

        except MySQLdb.Error, e:
            try:
                print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
            except IndexError:
                print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)

        MYSQL['cursor'].execute( SQL['REF']['select'], CONFIG['RAW']['REF']['environment'] )
        TEMP = MYSQL['cursor'].fetchall()

        # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
        if len( TEMP ) > 0:
            DINFO['ref_id']          = TEMP[0]['id']
            print ("[INFO] MYSQL : Reference id = %(id)s, build_id = %(build_id)s" % TEMP[0])
        else:
            print "[ERROR] MYSQL : Can not process reference TCT"
            exit(1)




        for suite in CONFIG['RAW']['REF']['SUITE'].keys():

            VALUES = {
                'trbs_ref_id'   : DINFO['ref_id'],
                'name'          : suite,
                'total'         : CONFIG['RAW']['REF']['SUITE'][suite]['total_case'],
                'pass'          : CONFIG['RAW']['REF']['SUITE'][suite]['pass_case'],
                'pass_rate'     : CONFIG['RAW']['REF']['SUITE'][suite]['pass_rate'],
                'fail'          : CONFIG['RAW']['REF']['SUITE'][suite]['fail_case'],
                'fail_rate'     : CONFIG['RAW']['REF']['SUITE'][suite]['fail_rate'],
                'block'         : CONFIG['RAW']['REF']['SUITE'][suite]['block_case'],
                'block_rate'    : CONFIG['RAW']['REF']['SUITE'][suite]['block_rate'],
                'na'            : CONFIG['RAW']['REF']['SUITE'][suite]['na_case'],
                'na_rate'       : CONFIG['RAW']['REF']['SUITE'][suite]['na_rate']
            }

            SQL['REF']['select_suite'] = (
                "SELECT * "
                "FROM trbs_ref_suite "
                "WHERE trbs_ref_id = %(trbs_ref_id)s AND name = %(name)s"
            )

            MYSQL['cursor'].execute( SQL['REF']['select_suite'], VALUES )
            TEMP = MYSQL['cursor'].fetchall()


            table = "trbs_ref_suite"
            sql = ""

            if len( TEMP ) > 0:
                sql = makeUpdateSQL( table, VALUES , TEMP[0]['id'])
                print ("[INFO] MYSQL : Updated REF Suite, id = %(id)s, name = %(name)s" % TEMP[0])

            else:
                sql = makeInsertSQL( table, VALUES )
                print "[INFO] MYSQL : INSERT to", table, ", trbs_ref_id =", DINFO['ref_id'], ", name =", suite


            try:
                MYSQL['cursor'].execute( sql )
                MYSQL['connection'].commit()


            except MySQLdb.Error, e:
                try:
                    print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
                except IndexError:
                    print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)



    SQL['TCT'] = {}

    # select tct
    SQL['TCT']['select'] = (
        "SELECT * "
        "FROM trbs_tct "
        "WHERE sr_name = %(sr)s AND snapshot_num = %(snapshot_num)s AND tct_profile = %(tct_profile)s ORDER BY id DESC"
    )

    MYSQL['cursor'].execute( SQL['TCT']['select'], DINFO )
    TEMP = MYSQL['cursor'].fetchall()

    pcnt = 0
    if int(CONFIG['RAW']['TCT']['COUNT']['total_case']) > 0:
        pcnt = round( (float(CONFIG['RAW']['TCT']['COUNT']['pass_case'])/float(CONFIG['RAW']['TCT']['COUNT']['total_case']))*100, 2 )

    # if reference is not exists, then value of ref_id is -1
    ref_id = "-1"

    if isExistRef :
        ref_id = DINFO['ref_id']

    VALUES = {
        'sr_status_id'  : DINFO['sr_status_id'],
        'ref_id'        : ref_id,
        'sr_name'       : DINFO['sr'],
        'snapshot_num'  : DINFO['snapshot_num'],
        'profile'       : CONFIG['RAW']['TCT']['environment']['tct_profile'],
        'total'         : CONFIG['RAW']['TCT']['COUNT']['total_case'],
        'pass'          : CONFIG['RAW']['TCT']['COUNT']['pass_case'],
        'fail'          : CONFIG['RAW']['TCT']['COUNT']['fail_case'],
        'block'         : CONFIG['RAW']['TCT']['COUNT']['block_case'],
        'na'            : CONFIG['RAW']['TCT']['COUNT']['na_case'],
        'pcnt'          : pcnt,
        'plan_name'     : CONFIG['RAW']['TCT']['plan_name'],
        'time_start'    : CONFIG['RAW']['TCT']['start_at'],
        'time_end'      : CONFIG['RAW']['TCT']['end_at'],
        'build_id'      : CONFIG['RAW']['TCT']['environment'].get('build_id'),
        'device_id'     : CONFIG['RAW']['TCT']['environment'].get('device_id'),
        'device_model'  : CONFIG['RAW']['TCT']['environment'].get('device_model'),
        'device_name'   : CONFIG['RAW']['TCT']['environment'].get('device_name'),
        'device_host'   : CONFIG['RAW']['TCT']['environment'].get('device_host'),
        'manufacturer'  : CONFIG['RAW']['TCT']['environment'].get('manufacturer'),
        'tct_profile'   : CONFIG['RAW']['TCT']['environment'].get('tct_profile'),
        'tct_version'   : CONFIG['RAW']['TCT']['environment'].get('tct_version'),
        'url'           : CONFIG['RAW']['TCT']['url']
    }

    table = "trbs_tct"
    sql = ""


    if len( TEMP ) > 0:
        DINFO['trbs_tct_id'] = TEMP[0]['id']
        sql = makeUpdateSQL( table, VALUES , DINFO['trbs_tct_id'])
        print ("[Info] MYSQL : Updated TCT, id = %(id)s, sr_name = %(sr_name)s" % TEMP[0])

    else:
        sql = makeInsertSQL( table, VALUES )
        print "[INFO] MYSQL : INSERT to", table, ", build_id =", VALUES['build_id']

    try:
        MYSQL['cursor'].execute( sql )
        MYSQL['connection'].commit()


    except MySQLdb.Error, e:
        try:
            print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
        except IndexError:
            print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)



    MYSQL['cursor'].execute( SQL['TCT']['select'], DINFO )
    TEMP = MYSQL['cursor'].fetchall()

    # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
    if len( TEMP ) > 0:
        DINFO['trbs_tct_id'] = TEMP[0]['id']
        print ("[INFO] MYSQL : TCT id = %(id)s, build_id = %(build_id)s" % TEMP[0])
    else:
        print "[ERROR] MYSQL : Can not process TCT"
        exit(1)

    # Clear previous records
    clear_query = "DELETE FROM trbs_tct_suite WHERE trbs_tct_id=%s"
    clear_query_data = (DINFO.get('trbs_tct_id', -1),)
    MYSQL['cursor'].execute( clear_query, clear_query_data )

    for suite in CONFIG['RAW']['TCT']['SUITE'].keys():

        VALUES = {
            'trbs_tct_id'   : DINFO['trbs_tct_id'],
            'name'          : suite,
            'total'         : CONFIG['RAW']['TCT']['SUITE'][suite]['total_case'],
            'pass'          : CONFIG['RAW']['TCT']['SUITE'][suite]['pass_case'],
            'pass_rate'     : CONFIG['RAW']['TCT']['SUITE'][suite]['pass_rate'],
            'fail'          : CONFIG['RAW']['TCT']['SUITE'][suite]['fail_case'],
            'fail_rate'     : CONFIG['RAW']['TCT']['SUITE'][suite]['fail_rate'],
            'block'         : CONFIG['RAW']['TCT']['SUITE'][suite]['block_case'],
            'block_rate'    : CONFIG['RAW']['TCT']['SUITE'][suite]['block_rate'],
            'na'            : CONFIG['RAW']['TCT']['SUITE'][suite]['na_case'],
            'na_rate'       : CONFIG['RAW']['TCT']['SUITE'][suite]['na_rate']
        }
        
        # ADD detail colume
        if 'detail' in CONFIG['RAW']['TCT']['SUITE'][suite]:
            VALUES['detail'] =  CONFIG['RAW']['TCT']['SUITE'][suite]['detail']

        SQL['TCT']['select_suite'] = (
            "SELECT * "
            "FROM trbs_tct_suite "
            "WHERE trbs_tct_id = %(trbs_tct_id)s AND name = %(name)s"
        )

        MYSQL['cursor'].execute( SQL['TCT']['select_suite'], VALUES )
        TEMP = MYSQL['cursor'].fetchall()

        table = "trbs_tct_suite"
        sql = ""

        if len( TEMP ) > 0:
            sql = makeUpdateSQL( table, VALUES, TEMP[0]['id'] )
            print ("[INFO] MYSQL : Updated TCT Suite, id = %(id)s, name = %(name)s" % TEMP[0])

        else:
            sql = makeInsertSQL( table, VALUES )
            print "[INFO] MYSQL : INSERT to", table, ", trbs_tct_id =", DINFO['trbs_tct_id'], ", name =", suite

        try:
            #print sql
            #exit()
            MYSQL['cursor'].execute( sql )
            MYSQL['connection'].commit()


        except MySQLdb.Error, e:
            try:
                print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
            except IndexError:
                print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)




    SQL['SMOKES'] = {}
    # select smokes
    SQL['SMOKES']['select'] = (
        "SELECT * "
        "FROM trbs_smoke "
        "WHERE sr_name = %(sr)s AND snapshot_num = %(snapshot_num)s AND profile = %(tct_profile)s ORDER BY id DESC"
    )

    VALUES = {
        'sr_status_id'  : DINFO['sr_status_id'],
        'sr_name'       : DINFO['sr'],
        'snapshot_num'  : DINFO['snapshot_num'],
        'profile'       : CONFIG['RAW']['TCT']['environment']['tct_profile'],
        'total'         : CONFIG['RAW']['SMOKES']['COUNT']['total_case'],
        'pass'          : CONFIG['RAW']['SMOKES']['COUNT']['pass_case'],
        'fail'          : CONFIG['RAW']['SMOKES']['COUNT']['fail_case'],
        'pcnt'          : round( (float(CONFIG['RAW']['SMOKES']['COUNT']['pass_case'])/float(CONFIG['RAW']['SMOKES']['COUNT']['total_case']))*100, 2 ),
        'time_start'    : CONFIG['RAW']['TCT']['start_at'],
        'time_end'      : CONFIG['RAW']['TCT']['start_at'],
        'url'           : CONFIG['RAW']['TCT']['url']
    }

    MYSQL['cursor'].execute( SQL['SMOKES']['select'], DINFO )
    TEMP = MYSQL['cursor'].fetchall()

    table = "trbs_smoke"
    sql = ""

    if len( TEMP ) > 0:
        DINFO['trbs_smoke_id'] = TEMP[0]['id']
        sql = makeUpdateSQL( table, VALUES, DINFO['trbs_smoke_id'] )
        print ("[INFO] MYSQL : Updated SMOKE, id = %(id)s, sr_name = %(sr_name)s" % TEMP[0])

    else:
        sql = makeInsertSQL( table, VALUES )
        print "[INFO] MYSQL : INSERT to", table


    try:
        MYSQL['cursor'].execute( sql )
        MYSQL['connection'].commit()

    except MySQLdb.Error, e:
        try:
            print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
        except IndexError:
            print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)



    MYSQL['cursor'].execute( SQL['SMOKES']['select'], DINFO )
    TEMP = MYSQL['cursor'].fetchall()

    # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
    if len( TEMP ) > 0:
        DINFO['trbs_smoke_id'] = TEMP[0]['id']
        print ("[INFO] MYSQL : SMOKE id = %(id)s" % TEMP[0])
    else:
        print "[ERROR] MYSQL : Can not process SMOKE"
        exit(1)

    #pprint.pprint( CONFIG['RAW']['SMOKES'] )
    #exit()



    for suite in CONFIG['RAW']['SMOKES']['SUITE'].keys():

        VALUES = {
            'trbs_smoke_id' : DINFO['trbs_smoke_id'],
            'name'          : suite,
            'pass'          : CONFIG['RAW']['SMOKES']['SUITE'][suite]['COUNT']['pass_case'],
            'fail'          : CONFIG['RAW']['SMOKES']['SUITE'][suite]['COUNT']['fail_case'],
        }

        SQL['SMOKES']['select_suite'] = (
            "SELECT * "
            "FROM trbs_smoke_suite "
            "WHERE trbs_smoke_id = %(trbs_smoke_id)s AND name = %(name)s"
        )


        MYSQL['cursor'].execute( SQL['SMOKES']['select_suite'], VALUES )
        TEMP = MYSQL['cursor'].fetchall()


        table = "trbs_smoke_suite"
        sql = ""

        if len( TEMP ) > 0:
            DINFO['trbs_smoke_suite_id'] = TEMP[0]['id']
            sql = makeUpdateSQL( table, VALUES , DINFO['trbs_smoke_suite_id'] )
            print ("[INFO] MYSQL : Updated SMOKE Suite, id = %(id)s, name = %(name)s" % TEMP[0])

        else:
            sql = makeInsertSQL( table, VALUES )
            print "[INFO] MYSQL : INSERT to", table, ", trbs_smoke_id =", DINFO['trbs_smoke_id'], ", name =", suite

        try:
            #print sql
            #exit()

            MYSQL['cursor'].execute( sql )
            MYSQL['connection'].commit()

        except MySQLdb.Error, e:
            try:
                print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
            except IndexError:
                print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)


        # check
        MYSQL['cursor'].execute( SQL['SMOKES']['select_suite'], VALUES )
        TEMP = MYSQL['cursor'].fetchall()

        if len( TEMP ) == 0:
            print "[ERROR] MYSQL : Can not process SMOKE Suite"
        else:
            DINFO['trbs_smoke_suite_id'] = TEMP[0]['id']


        for testcase in CONFIG['RAW']['SMOKES']['SUITE'][suite]['TESTCASE'].keys():

            VALUES = {
                'trbs_smoke_suite_id' : DINFO['trbs_smoke_suite_id'],
                'name'                : testcase,
                'result'              : CONFIG['RAW']['SMOKES']['SUITE'][suite]['TESTCASE'][testcase]['passed']
            }

            # ADD detail colume
            if 'detail' in CONFIG['RAW']['SMOKES']['SUITE'][suite]['TESTCASE'][testcase]:
                VALUES['detail'] = CONFIG['RAW']['SMOKES']['SUITE'][suite]['TESTCASE'][testcase]['detail']

            #pprint.pprint( VALUES )
            #exit()


            SQL['SMOKES']['select_suite_test'] = (
                "SELECT * "
                "FROM trbs_smoke_suite_test "
                "WHERE trbs_smoke_suite_id = %(trbs_smoke_suite_id)s AND name = %(name)s"
            )

            MYSQL['cursor'].execute( SQL['SMOKES']['select_suite_test'], VALUES )
            TEMP = MYSQL['cursor'].fetchall()

            table = "trbs_smoke_suite_test"
            sql = ""


            if len( TEMP ) > 0:
                sql = makeUpdateSQL( table, VALUES , TEMP[0]['id'] )
                print ("[INFO] MYSQL : Updated SMOKE Suite Test, id = %(id)s, name = %(name)s" % TEMP[0])
            else:
                sql = makeInsertSQL( table, VALUES )
                print "[INFO] MYSQL : INSERT to", table, ", trbs_smoke_suite_id =", DINFO['trbs_smoke_suite_id'], ", name =", testcase

            try:
                #print sql
                #exit()

                MYSQL['cursor'].execute( sql )
                MYSQL['connection'].commit()

            except MySQLdb.Error, e:
                try:
                    print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
                except IndexError:
                    print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)



    SQL['PERFS'] = {}

    # If perf is existed, then insert into DB.
    isExistPerf = True

    if 'DEVICE' not in CONFIG['RAW']['PERFS'] :
        isExistPerf = False

    if isExistPerf :
        # select perfs
        SQL['PERFS']['select'] = (
            "SELECT * "
            "FROM trbs_perf "
            "WHERE sr_name = %(sr)s AND snapshot_num = %(snapshot_num)s AND profile = %(tct_profile)s ORDER BY id DESC"
        )

        MYSQL['cursor'].execute( SQL['PERFS']['select'], DINFO )
        TEMP = MYSQL['cursor'].fetchall()


        VALUES = {
            'sr_status_id'    : DINFO['sr_status_id'],
            'sr_name'         : DINFO['sr'],
            'snapshot_num'    : DINFO['snapshot_num'],
            'profile'         : CONFIG['RAW']['TCT']['environment']['tct_profile'],
            'device_core'     : CONFIG['RAW']['PERFS']['DEVICE']['Core_Nums'],
            'device_dvfs'     : CONFIG['RAW']['PERFS']['DEVICE']['Def._DVFS_governor'],
            'device_freq'     : CONFIG['RAW']['PERFS']['DEVICE']['Frequency_range'],
            'device_kernel'   : CONFIG['RAW']['PERFS']['DEVICE']['Kernel_ver.'],
            'device_platform' : CONFIG['RAW']['PERFS']['DEVICE']['Platform_ver.'],
            'total'           : CONFIG['RAW']['PERFS']['COUNT']['total_case'],
            'pass'            : CONFIG['RAW']['PERFS']['COUNT']['pass_case'],
            'fail'            : CONFIG['RAW']['PERFS']['COUNT']['fail_case'],
            'pcnt'            : round( (float(CONFIG['RAW']['PERFS']['COUNT']['pass_case'])/float(CONFIG['RAW']['PERFS']['COUNT']['total_case']))*100, 2 ),
            'time_start'      : CONFIG['RAW']['TCT']['start_at'],
            'time_end'        : CONFIG['RAW']['TCT']['start_at'],
            'url'             : CONFIG['RAW']['TCT']['url']
        }

        table = "trbs_perf"
        sql = ""

        if len( TEMP ) > 0:
            DINFO['trbs_perf_id'] = TEMP[0]['id']
            sql = makeUpdateSQL( table, VALUES,DINFO['trbs_perf_id'] )
            print ("[INFO] MYSQL : Updated PERF, id = %(id)s, sr_name = %(sr_name)s" % TEMP[0])

        else:
            sql = makeInsertSQL( table, VALUES )
            print "[INFO] MYSQL : INSERT to", table

        try:
            MYSQL['cursor'].execute( sql )
            MYSQL['connection'].commit()


        except MySQLdb.Error, e:
            try:
                print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
            except IndexError:
                print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)



        MYSQL['cursor'].execute( SQL['PERFS']['select'], DINFO )
        TEMP = MYSQL['cursor'].fetchall()

        # 결과가 1개 이거나 아니면 latest 결과가 정답일 것이라 전제
        if len( TEMP ) > 0:
            DINFO['trbs_perf_id'] = TEMP[0]['id']
            print ("[INFO] MYSQL : PERF id = %(id)s" % TEMP[0])
        else:
            print "[ERROR] MYSQL : Can not process PERF"
            exit(1)



        #pprint.pprint( CONFIG['RAW']['PERFS'] )
        #exit()

        for suite in CONFIG['RAW']['PERFS']['SUITE'].keys():

            #pprint.pprint( CONFIG['RAW']['PERFS']['SUITE'][suite] )
            #pprint.pprint( DINFO )
            #exit()

            VALUES = {
                'trbs_perf_id' : DINFO['trbs_perf_id'],
                'name'          : suite,
                'pass'          : CONFIG['RAW']['PERFS']['SUITE'][suite]['COUNT']['pass_case'],
                'fail'          : CONFIG['RAW']['PERFS']['SUITE'][suite]['COUNT']['fail_case'],
                'total'         : CONFIG['RAW']['PERFS']['SUITE'][suite]['COUNT']['total_case']
            }

            #pprint.pprint( VALUES )
            #exit()

            SQL['PERFS']['select_suite'] = (
                "SELECT * "
                "FROM trbs_perf_suite "
                "WHERE trbs_perf_id = %(trbs_perf_id)s AND name = %(name)s"
            )

            MYSQL['cursor'].execute( SQL['PERFS']['select_suite'], VALUES )
            TEMP = MYSQL['cursor'].fetchall()

            table = "trbs_perf_suite"
            sql = ""

            if len( TEMP ) > 0:
                DINFO['trbs_perf_suite_id'] = TEMP[0]['id']
                sql = makeUpdateSQL( table, VALUES, DINFO['trbs_perf_suite_id'] )
                print ("[INFO] MYSQL : Updated PERF Suite, id = %(id)s, name = %(name)s" % TEMP[0])

            else:
                sql = makeInsertSQL( table, VALUES )
                print "[INFO] MYSQL : INSERT to", table, ", trbs_perf_id =", DINFO['trbs_perf_id'], ", name =", suite


            try:
                MYSQL['cursor'].execute( sql )
                MYSQL['connection'].commit()

            except MySQLdb.Error, e:
                try:
                    print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
                except IndexError:
                    print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)


            MYSQL['cursor'].execute( SQL['PERFS']['select_suite'], VALUES )
            TEMP = MYSQL['cursor'].fetchall()


            if len( TEMP ) == 0:
                print "[ERROR] MYSQL : Can not process PERF Suite"
            else:
                DINFO['trbs_perf_suite_id'] = TEMP[0]['id']



            for testcase in CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'].keys():

                VALUES = {
                    'trbs_perf_suite_id' : DINFO['trbs_perf_suite_id'],
                    'name'               : testcase,
                    'actualperf'         : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['ActualPerf'],
                    'criteria'           : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['Criteria'],
                    'expectedperf'       : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['ExpectedPerf'],
                    'range'              : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['Range'],
                    'result'             : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['Result'],
                    'unit'               : CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['Unit']
                }

                # ADD detail colume
                if 'detail' in CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]:
                    VALUES['detail'] = CONFIG['RAW']['PERFS']['SUITE'][suite]['TESTCASE'][testcase]['detail']

                #pprint.pprint( VALUES )
                #exit()


                SQL['PERFS']['select_suite_test'] = (
                    "SELECT * "
                    "FROM trbs_perf_suite_test "
                    "WHERE trbs_perf_suite_id = %(trbs_perf_suite_id)s AND name = %(name)s"
                )

                MYSQL['cursor'].execute( SQL['PERFS']['select_suite_test'], VALUES )
                TEMP = MYSQL['cursor'].fetchall()

                table = "trbs_perf_suite_test"
                sql = ""

                if len( TEMP ) > 0:
                    sql = makeUpdateSQL( table, VALUES, TEMP[0]['id'] )
                    print ("[INFO] MYSQL : Updated PERF Suite Test, id = %(id)s, name = %(name)s" % TEMP[0])
                else:
                    sql = makeInsertSQL( table, VALUES )
                    print "[INFO] MYSQL : INSERT to", table, ", trbs_perf_suite_id =", DINFO['trbs_perf_suite_id'], ", name =", testcase


                try:
                    MYSQL['cursor'].execute( sql )
                    MYSQL['connection'].commit()

                except MySQLdb.Error, e:
                    try:
                        print "[ERROR] MYSQL : [%d]: %s (%s)" % (e.args[0], e.args[1], sql)
                    except IndexError:
                        print "[ERROR] MYSQL : %s (%s)" % (str(e), sql)


    snapshot = CONFIG['RAW']['TCT']['environment'].get('build_id', '')
    insert_test_stage(CONFIG['RAW'], MYSQL, DINFO['sr_status_id'], snapshot, \
                      isExistRef , isExistPerf, CONFIG['RAW'].get('INFO'))

    exit(0)

