#!/usr/bin/env python3.7

import codecs
import csv
import logging
import logging.config
import os
import shutil

import pandas as pd

import common


def get_file_prefix(tab_name: str) -> str:
    return {
        "Deutsch": "DE",
        "Englisch": "GB",
        "Spanisch": "ES",
        "Französisch": "FR",
        "Italienisch": "IT",
        "EAN UPC": "EAN"
    }.get(tab_name, "")


def extract_csv(in_file: str, out_path: str):
    xl = pd.ExcelFile(in_file)

    ws_names = xl.sheet_names

    for ws_name in ws_names:
        out_file = "{}{}.csv".format(
            get_file_prefix(ws_name),
            os.path.basename(os.path.splitext(in_file)[0])).replace(" ", "_")
        out_file_full = os.path.join(out_path, out_file)
        logging.info("Writing '%s'...", out_file)
        df = xl.parse(ws_name)
        art_hdr_name = df.columns.tolist()[1]
        df[art_hdr_name] = "ADI" + df[art_hdr_name] + "_000"
        df.to_csv(out_file_full,
                  index=False,
                  sep=";",
                  encoding="utf-8",
                  quoting=csv.QUOTE_NONNUMERIC)


def process(project_root: str) -> None:
    path_in = os.path.join(project_root, "in")
    path_out = os.path.join(project_root, "out")
    path_proc = os.path.join(project_root, "processed")
    path_error = os.path.join(project_root, "error")

    if not os.path.exists(path_proc):
        os.mkdir(path_proc)

    if not os.path.exists(path_error):
        os.mkdir(path_error)

    files = os.listdir(path_in)
    num_files = len(files)

    logging.info(f"Found %d file(s)...", num_files)

    if num_files == 0:
        return

    for f in files:
        in_file = os.path.join(path_in, f)
        proc_file = os.path.join(path_proc, f)

        logging.info("Extracting CSV files from '%s'...", in_file)

        try:
            extract_csv(in_file, path_out)
            shutil.move(in_file, proc_file)
        except Exception as ex:
            logging.exception(ex)
            shutil.move(in_file, os.path.join(path_error, f))


def main() -> None:
    data_root = common.get_data_root()
    project_root = os.path.join(data_root, "Matching_Adidas_Click_Texte")

    path_log = os.path.join(project_root, "log")

    if not os.path.exists(path_log):
        os.mkdir(path_log)

    log_file = os.path.join(
        path_log,
        os.path.basename(os.path.splitext(__file__)[0]) + ".log")
    logging.config.dictConfig(common.get_logging_config(log_file))

    process(project_root)

    print("Done.")


if __name__ == "__main__":
    try:
        main()
    except Exception as ex:
        print(ex)
