#!/usr/bin/env python3
#
# Copyright (C) 2017 Samsung Electronics. Co,. Ltd.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; version 2
#    of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

import os
import re
import json
import sys
import traceback
import copy
import json
import urllib3
import requests
import pprint
import xlrd

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

import job_dtr_db_writer
import datetime


#####################  1. DTR Version Info #####################
def change_version_data(input_version):
    p = re.compile('tizen-.*_[0-9]{8}.[0-9]')

    url = input_version
    m = p.search(url)
    version = m.group()

    return version

def dtr_ver_info_export(sheet):
    ncol = sheet.ncols
    nrow = sheet.nrows

    total_results = {}
    total_results['tizen_version'] = []
    total_results['url_list']      = []

    total_results['row']           = nrow
    total_results['col']           = ncol

    test_date = datetime.datetime.now()
    total_results['test_date'] = test_date.strftime('%Y-%m-%d')


    ver_list = []
    url_name = []
    real_url = []
    for row in range(0, nrow):
        ver_list.append(sheet.cell(row, 0).value)
        url_name.append(sheet.cell(row, 1).value)
        real_url.append(sheet.cell(row, 2).value)

    for row in range(0, nrow):
        total_results[ver_list[row]]  = []
        total_results[url_name[row]]  = []
        total_results[url_name[row]].append(real_url[row])
        total_results['tizen_version'].append(ver_list[row])
        total_results['url_list'].append(url_name[row])

    for index, url_list in enumerate(total_results['url_list']):
        tizen_version = change_version_data("".join(total_results[url_list]))
        total_results[ver_list[index]] = tizen_version

    return total_results

#####################  2. DTR Smoke Test result  #####################
def dtr_smoke_menu_export(sheet, test_ver_info_dict):
    ncol = sheet.ncols
    nrow = sheet.nrows

    total_results = {}
    total_results['test_date'] = []
    total_results['var_list']  = []
    total_results['ver_list']  = []
    total_results['env_list']  = []
    total_results['tar_list']  = []

    total_results['row']          = nrow
    total_results['col']          = ncol

    test_date = datetime.datetime.now()

    var_list = []
    ver_list = []
    env_list = []
    tar_list = []

    for col in range(0, ncol):
        var_list.append(sheet.cell(0, col).value)
        total_results['var_list'].append(var_list[col])

        ver_list.append(sheet.cell(1, col).value)
        total_results['ver_list'].append(ver_list[col])

        env_list.append(sheet.cell(2, col).value)
        total_results['env_list'].append(env_list[col])

        tar_list.append(sheet.cell(3, col).value)
        total_results['tar_list'].append(tar_list[col])

    for col in range(0, ncol):
        total_results[var_list[col]] = []
        total_results[var_list[col]].append(ver_list[col])
        total_results[var_list[col]].append(env_list[col])
        total_results[var_list[col]].append(tar_list[col])
        total_results[var_list[col]].append(test_date.strftime('%Y-%m-%d'))

        if ver_list[col] in test_ver_info_dict['tizen_version']:
            total_results[var_list[col]].append(test_ver_info_dict[ver_list[col]])

#    pprint.pprint(total_results)

    return total_results


def dtr_smoke_result_export(sheet):
    ncol = sheet.ncols
    nrow = sheet.nrows

    total_results = {}
    total_results['test_cases']    = []
    total_results['comments']  = []

    total_results['row'] = nrow
    total_results['col'] = ncol

    test_case_list = []
    comment_list   = []
    for row in range(0, nrow):
        test_case_list.append(sheet.cell(row, 0).value)
        comment_list.append(sheet.cell(row, ncol-1).value)

    for i in range(0, len(test_case_list)):
        total_results[test_case_list[i]] = []
        total_results['test_cases'].append(test_case_list[i])
        total_results['comments'].append(comment_list[i])

    for row in range(0, nrow):
        for col in range(1, ncol-1):
            try:
                test_suite = total_results['test_cases'][row]
                total_results[test_suite].append(sheet.cell(row, col).value)
            except Exception as ex:
                print('error' , ex)

    return total_results

def dtr_smoke_comment_DB_export(MIDDLE_INFO, arg_name):
    total_results = {}
    total_results[arg_name] = []

    case_list    = []
    comment_list = []

    for test_case in MIDDLE_INFO['smoke_result_data']['test_cases']:
        case_list.append(test_case)
    for comment in MIDDLE_INFO['smoke_result_data']['comments']:
        comment_list.append(comment)

    for i in range(0, len(case_list)):
        total_results[arg_name].append((case_list[i],comment_list[i]))

#    pprint.pprint(total_results)

    return total_results

##################### 1. 2. Combine #########################
def dtr_target_lookup_DB_export(MIDDLE_INFO, arg_name):
    total_results = {}
    total_results[arg_name] = []
    var_list = ["test_info", "tizen_version", "tizen_environ", "tizen_target", "test_date", "tizen_release_version"]

    lookup_temp_list = []
    for menu in MIDDLE_INFO['smoke_menu_data']['var_list']:
        lookup_temp_list.append(menu)
        for i in range(0, len(MIDDLE_INFO['smoke_menu_data'][menu])):
            lookup_temp_list.append(MIDDLE_INFO['smoke_menu_data'][menu][i])


    lookup_var_list = []
    col = MIDDLE_INFO['smoke_menu_data']['col']
    row = MIDDLE_INFO['smoke_menu_data']['row']


    for i in range (0, col):
        test_info             = lookup_temp_list[i*len(var_list)]
        tizen_version         = lookup_temp_list[i*len(var_list) + 1]
        tizen_environ         = lookup_temp_list[i*len(var_list) + 2]
        tizen_target          = lookup_temp_list[i*len(var_list) + 3]
        test_date             = lookup_temp_list[i*len(var_list) + 4]
        tizen_release_version = lookup_temp_list[i*len(var_list) + 5]
        total_results[arg_name].append( (test_info, tizen_version, tizen_environ, tizen_target, test_date, tizen_release_version) )

#    pprint.pprint(total_results)

    return total_results


def dtr_smoke_value_DB_export(MIDDLE_INFO, arg_name):
    total_results = {}
    total_results['var_list'] = []
    total_results['test_case'] = []
    total_results['smoke_result_list'] = []
    total_results[arg_name] = []

    for menus in MIDDLE_INFO['smoke_menu_data']['var_list']:
        total_results['var_list'].append(menus)

    for test_case in MIDDLE_INFO['smoke_result_data']['test_cases']:
        total_results['test_case'].append(test_case)

    case_list = []
    for test_case in MIDDLE_INFO['smoke_result_data']['test_cases']:
        case_list.append(test_case)

    result_list = []
    for case in case_list:
        total_results['smoke_result_list'].append(MIDDLE_INFO['smoke_result_data'][case])

    for case_idx, test_case_value in enumerate(total_results['test_case']):
        tmp_value = total_results['smoke_result_list'][case_idx]
        for value_idx, result_value in enumerate(tmp_value):
            total_results[arg_name].append((result_value, test_case_value, case_idx+1, value_idx+1))

#    pprint.pprint(total_results)

    return total_results


##################### General export #######################
def dtr_general_menu_export(sheet, arg_name):
    ncol = sheet.ncols
    nrow = sheet.nrows

    total_results = {}
    total_results[arg_name] = []

    total_results['row'] = nrow
    total_results['col'] = ncol

    test_date = datetime.datetime.now()
    total_results['test_date'] = test_date.strftime('%Y-%m-%d')

    for row in range(0, nrow):
        for col in range(0, ncol):
            try:
                total_results[arg_name].append(sheet.cell(row, col).value)
            except Exception as ex:
                print('error' , ex)

    return total_results

def dtr_general_result_export(sheet, arg_name):
    ncol = sheet.ncols
    nrow = sheet.nrows

    total_results           = {}
    total_results['nrow']   = nrow
    total_results['ncol']   = ncol
    total_results[arg_name] = []

    test_date = datetime.datetime.now()
    total_results['test_date'] = test_date.strftime('%Y-%m-%d')

    tbt_lists = []
    for i in range(0, nrow):
        tbt_lists = sheet.row_values(i)
        tbt_lists.insert(0, total_results['test_date'])
        total_results[arg_name].append(tuple(tbt_lists))

    return total_results

##################### Main ##################################
def main():

    # complete memory
    test_ver_info_dict     = {}

    smoke_menu_dict        = {}
    smoke_result_dict      = {}
    smoke_comment_dict     = {}
    smoke_result_DB_dict   = {}

    dtr_target_lookup_dict = {}
    dtr_smoke_result_dict  = {}

    tbt_menu_dict          = {}
    tbt_result_dict        = {}

    sample_menu_dict       = {}
    sample_result_dict     = {}

    unresolved_menu_dict   = {}
    unresolved_result_dict = {}

    # open excel
    excel_document = xlrd.open_workbook('Daily_Regression_Test_Result_ver1_format.xlsx')

    # export each tab contents
    test_ver_info_sheet     = excel_document.sheet_by_name('version_info')

    smoke_menu_sheet        = excel_document.sheet_by_name('smoke_menu')
    smoke_result_sheet      = excel_document.sheet_by_name('smoke_data')

    tbt_menu_sheet          = excel_document.sheet_by_name('tbt_menu')
    tbt_result_sheet        = excel_document.sheet_by_name('tbt_data')

    sample_menu_sheet       = excel_document.sheet_by_name('sample_menu')
    sample_result_sheet     = excel_document.sheet_by_name('sample_data')

    unresolved_menu_sheet   = excel_document.sheet_by_name('unresolved_menu')
    unresolved_result_sheet = excel_document.sheet_by_name('unresolved_data')

    ## 1. DTR test ver. data
    test_ver_info_dict      = dtr_ver_info_export(test_ver_info_sheet)

    ## 2. DTR Smoke data
    smoke_menu_dict         = dtr_smoke_menu_export(smoke_menu_sheet, test_ver_info_dict)
    smoke_result_dict       = dtr_smoke_result_export(smoke_result_sheet)

    MIDDLE_INFO = {
        'test_ver_info_data'     :  test_ver_info_dict,
        'smoke_menu_data'        :  smoke_menu_dict,
        'smoke_result_data'      :  smoke_result_dict,
    }

    target_lookup_DB_dict   = dtr_target_lookup_DB_export(MIDDLE_INFO, "lookup_DB_values")
    smoke_comment_DB_dict   = dtr_smoke_comment_DB_export(MIDDLE_INFO, "smoke_comment_DB_values")
    smoke_value_DB_dict    = dtr_smoke_value_DB_export(MIDDLE_INFO, "smoke_value_DB_values")

    ## 3. DTR TBT data
    tbt_menu_dict           = dtr_general_menu_export(tbt_menu_sheet, "tbt_menus")
    tbt_result_dict         = dtr_general_result_export(tbt_result_sheet, "tbt_DB_values")

    ## 4. DTR sample data
    sample_menu_dict        = dtr_general_menu_export(sample_menu_sheet, "sample_menus")
    sample_result_dict      = dtr_general_result_export(sample_result_sheet, "sample_DB_values")

    ## 5. DTR unresolved data
    unresolved_menu_dict    = dtr_general_menu_export(unresolved_menu_sheet, "unresolved_menus")
    unresolved_result_dict  = dtr_general_result_export(unresolved_result_sheet, "unresolved_DB_values")

    TOTAL_INFO = {
        'test_ver_info_data'     :  test_ver_info_dict,
        'smoke_menu_data'        :  smoke_menu_dict,
        'smoke_result_data'      :  smoke_result_dict,
        'smoke_comment_data'     :  smoke_comment_DB_dict,
        'smoke_value_data'       :  smoke_value_DB_dict,
        'target_lookup_data'     :  target_lookup_DB_dict,
        'tbt_menu_data'          :  tbt_menu_dict,
        'tbt_result_data'        :  tbt_result_dict,
        'sample_menu_data'       :  sample_menu_dict,
        'sample_result_data'     :  sample_result_dict,
        'unresolved_menu_data'   :  unresolved_menu_dict,
        'unresolved_result_data' :  unresolved_result_dict,
    }

#    pprint.pprint(TOTAL_INFO)

    job_dtr_db_writer.main(TOTAL_INFO)

    return 0

if __name__ == '__main__':
    sys.exit(main())
