'''
Created on Apr 28, 2020 @author: Levi
'''
import os
# import string
import platform
from time import sleep
from datetime import datetime

import openpyxl as xl
import subprocess as sp
# import xml.etree.ElementTree as ET
from openpyxl.styles import Font
# from openpyxl.utils import get_column_letter
# from revisal.revisal_xml import unzip_rvs
from revisal.revisal_xml import get_revisal
from revisal.revisal_xml import Contract, Revisal
from xlsx_handler import parse_and_close

# this is not needed, root and tree are declared in main module, get
# revisal_xml is makes global root

# tree = ET.parse('S.C. MOZAIK CONSULTING SRL S.R.L. 17259191 Apr 21 2020 23_45_17.xml')
# root = tree.getroot()
# path = 'c:/Users/levi/Documents/DECEL/Revisal Hg500/Rapoarte/'
# unzip_rvs(path=path)
contracts = []

def header_create(sheet, headers=[]):
    if len(headers) == 0:
        for name in Revisal._fields:
            if name != 'contracts' and name != 'nume':
                headers.append(name)
        for c_name in Contract._fields:
            headers.append(c_name)
    for n, h in enumerate(sheet.iter_cols(min_row=1, max_col=len(headers), max_row=1)):
        h[0].value = headers[n]
    for f in sheet['A1:Y1'][0]:
        f.font = Font(bold=True)

def format_after(sheet, ref=None):
    if not ref:
        ref = f'A1:X{sheet.max_row}'
    sheet.freeze_panes = 'A2'
    sheet.auto_filter.ref = ref


book = xl.Workbook()
sh = book.create_sheet('revisal_xml', 0)
header_create(sh)

def file_open(file_name):
    abs_path = os.path.abspath(file_name)
    if platform.system() == 'Windows':
        sp.run(f'start {abs_path}', shell=True)
    elif platform.system() == 'Linux':
        sp.run(['xdg-open', f'{abs_path}'])
    else:
        raise NotImplementedError


for ind, elem in enumerate(get_revisal(5)):
    print(elem.nume)
    # sh[f'A{ind+2}'] = elem.nume
    sh[f'A{ind+2}'] = f'{elem.nume} {elem.prenume}'
    sh[f'B{ind+2}'] = elem.adresa
    sh[f'C{ind+2}'] = elem.cnp
    sh[f'D{ind+2}'] = elem.nationalitate
    sh[f'E{ind+2}'] = elem.tara
    sh[f'F{ind+2}'] = elem.tipact
    sh[f'G{ind+2}'] = elem.contracts.codcor
    data_contract = datetime.strptime(elem.contracts.datacontract, '%Y-%m-%d')
    sh[f'H{ind+2}'] = data_contract
    sh[f'H{ind+2}'].number_format = 'DD-MM-YY'
    sh[f'I{ind+2}'] = elem.contracts.tipcontract
    sh[f'J{ind+2}'] = elem.contracts.tipdurata
    sh[f'K{ind+2}'] = elem.contracts.timpmunca
    data_inceput = datetime.strptime(elem.contracts.datainceput, '%Y-%m-%d')
    sh[f'L{ind+2}'] = data_inceput
    sh[f'L{ind+2}'].number_format = 'DD-MM-YY'
    if elem.contracts.datasfarsit:
        data_sfarsit = datetime.strptime(elem.contracts.datasfarsit, '%Y-%m-%d')
    else:
        data_sfarsit = elem.contracts.datasfarsit
    sh[f'M{ind+2}'] = data_sfarsit
    sh[f'M{ind+2}'].number_format = 'DD-MM-YY'
    sh[f'N{ind+2}'] = elem.contracts.detalii
    sh[f'O{ind+2}'] = elem.contracts.numar
    sh[f'P{ind+2}'] = int(elem.contracts.salariu)
    sh[f'P{ind+2}'].number_format = '#,##0'
    sh[f'Q{ind+2}'] = elem.contracts.stare
    sh[f'R{ind+2}'] = elem.contracts.inceputsusp
    sh[f'S{ind+2}'] = elem.contracts.sfarsitsusp
    sh[f'T{ind+2}'] = elem.contracts.incetaresusp
    data_cons = datetime.strptime(elem.contracts.datacons, '%Y-%m-%d')
    sh[f'U{ind+2}'] = data_cons
    sh[f'U{ind+2}'].number_format = 'DD-MM-YY'
    if elem.contracts.dataincetare:
        data_incetare = datetime.strptime(elem.contracts.dataincetare, '%Y-%m-%d')
    else:
        data_incetare = elem.contracts.dataincetare
    sh[f'V{ind+2}'] = data_incetare
    sh[f'V{ind+2}'].number_format = 'DD-MM-YY'
    sh[f'W{ind+2}'] = elem.contracts.temei

# columns = string.ascii_uppercase[:23]
# for column in columns:
#     sh.column_dimensions[column].bestFit = True
col_dims = {'A', 'Q'}
# sh.column_dimensions['A'].auto_size = True
dims = {}
for row in sh.rows:
    for cell in row:
        if cell.value:
            dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.value))))
for col, value in dims.items():
    if col in col_dims:
        sh.column_dimensions[col].width = value + 1

format_after(sh)
# book_name = 'rvs.xlsx'
book_name = 'rvs_xml'
book_path = os.path.abspath(book_name) + 'xlsx'
# print(path)
while PermissionError:
    try:
        book.save(book_name + '.xlsx')
        # sp.run(f'start {book_path}', shell=True)
        file_open(book_name + '.xlsx')
        break
    except PermissionError as e:
        print(str(e))
        # input(f'close {book_path} and press enter to try again')
        parse_and_close(book_name)
        sleep(2)
        book.save(book_name + '.xlsx')
        # sp.run(f'start {book_path}', shell=True)
        file_open(book_name + '.xlsx')
        break
