# --- MEPA ---
# Read config file
# Read Excel file generated by Ready Pro
# Copy rows into Excel file generated by acquistinretepa
# Save
# Upload file to acquistinretepa portal (sostituzione integrale)

import os.path
import time

from xlrd import open_workbook
from xlutils.copy import copy
from xlutils.save import save
import chromedriver_autoinstaller
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By

from .supplier import Supplier  # , ScappamentoError


supplier_name = 'MEPA'


def update():
    # Config, filenames
    key_list = ['readypro_excel_filename',  # TODO: more consistency in <filename> vs <fully qualified path> stuff
                'mepa_excel_filename',
                'new_excel_filename',
                'target_path',
                'login_url',
                'user',
                'user_css',
                'password',
                'password_css',
                'login_butt_css',
                'login_popup_css',
                'file_input_css',
                'upload_butt_css',
                'catalogo_css',
                'sostituzione_css']
    mepa = Supplier(supplier_name, key_list)

    print(mepa)  # Title

    [readypro_excel_filename,
     mepa_excel_filename,
     new_excel_filename,
     target_path,
     login_url,
     user,
     user_css,
     password,
     password_css,
     login_butt_css,
     login_popup_css,
     file_input_css,
     upload_butt_css,
     catalogo_css,
     sostituzione_css] = mepa.val_list

    # TODO: add some info prints
    # Open and re-save excel file to fix mildly malformed files
    readypro_xls = open_workbook(readypro_excel_filename)
    save(readypro_xls, readypro_excel_filename+'.f')

    # Copy data from generated spreadsheet to downloaded to-edit one
    readypro_xls = open_workbook(readypro_excel_filename+'.f')
    mepa_xls_model = open_workbook(mepa_excel_filename, formatting_info=True)

    mepa_xls_new = copy(mepa_xls_model)

    mepa_sheet = mepa_xls_new.get_sheet(1)
    readypro_sheet = readypro_xls.sheet_by_index(0)  # get_sheet() throws an error

    # TODO: avoid empty rows when an invalid entry is skipped
    for i in range(1, readypro_sheet.nrows):  # rows (skip header)
        for j in range(0, 20):  # cols
            marca = False
            for m in range(14, 18):  # Marca (A-D) = campo 14 (14 0-based with offset)
                marca = marca or readypro_sheet.cell_value(i, m)

            if marca and readypro_sheet.cell_value(i, 1):  # CodArt Produttore = campo 1
                mepa_sheet.write(i, j, readypro_sheet.cell_value(i, j+1))  # offset read, column 0 is empty

    mepa_xls_new.save(os.path.join(target_path, new_excel_filename))

    chromedriver_autoinstaller.install()

    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--window-size=3840,2160')
    with webdriver.Chrome(options=options) as driver:
        # Login
        driver.get(login_url)

        pop_up_butt = driver.find_element_by_css_selector(login_popup_css)
        pop_up_butt.click()

        user_input = driver.find_element_by_css_selector(user_css)
        user_input.send_keys(user)

        pass_input = driver.find_element_by_css_selector(password_css)
        pass_input.send_keys(password)

        login_butt = driver.find_element_by_css_selector(login_butt_css)
        login_butt.click()

        catalogo_butt = WebDriverWait(driver, 5).until(ec.element_to_be_clickable((By.CSS_SELECTOR, catalogo_css)))
        catalogo_butt.click()

        sost_butt = WebDriverWait(driver, 5).until(ec.presence_of_element_located((By.CSS_SELECTOR, sostituzione_css)))
        sost_butt.click()

        file_input = WebDriverWait(driver, 10).until(ec.presence_of_element_located((By.CSS_SELECTOR, file_input_css)))
        file_input.send_keys(os.path.join(target_path, new_excel_filename))

        upload_butt = WebDriverWait(driver, 5).until(ec.presence_of_element_located((By.CSS_SELECTOR, upload_butt_css)))
        upload_butt.click()

        time.sleep(10)  # dirty, switch with something that checks portal output message


if __name__ == '__main__':
    update()
