#!/usr/bin/env python

__author__ = 'holger.knust'

import codecs
import csv
import logging
import os
import shutil
import time


def read_ean_lookup(ref_path):
    ref_dict = {}

    header_read = False
    header_names = []
    full_ref_path = os.path.join(ref_path, "Ref_SSW_FBA.csv")
    with codecs.open(full_ref_path, "rb", encoding='utf-8') as f:

        reader = csv.reader(f, delimiter=';')
        ean_idx = -1
        price_idx = -1
        item_no_idx = -1
        item_prod_idx = -1
        for row in reader:
            if header_read:
                ean = row[ean_idx].strip()
                price_euro = row[price_idx]
                item_no = row[item_no_idx]
                item_prod = row[item_prod_idx]
                price_conv = price_euro.replace(".", "").replace(",", ".")
                try:
                    price = float(price_conv)
                    ref_dict[ean] = [price,item_no, item_prod]
                except ValueError as ve:
                    logging.error(ve)
            else:
                ean_idx = row.index("VariationEAN")
                price_idx = row.index("PurchasePrice")
                item_no_idx = row.index("ItemNo")
                item_prod_idx = row.index("ItemProducer")
                row.pop(0)
                row.pop(0)
                header_names = row
                header_read = True

    return ref_dict, header_names


def convert_fba(in_file, out_file, ref_dict, headers):
    header_read = False
    sku_index = -1
    asin_index = -1
    prod_name_index = -1
    missing_ean = []
    with codecs.open(in_file, "r", encoding='utf-8') as f, codecs.open(out_file, "w", encoding='utf-8') as of:
        reader = csv.reader(f, delimiter='\t')
        writer = csv.writer(of, delimiter=';')

        total = 0.0
        for row in reader:
            if header_read:
                sku = row[sku_index]
                asin = row[asin_index]
                prod_name = row[prod_name_index]

                if sku and sku.find('_fba') > -1:
                    ean = sku.replace('_fba', '').strip()
                    if ean in ref_dict:
                        ref_values = ref_dict[ean]
                        purch_price = ref_values.pop(0)
                        writer.writerow([sku,asin,prod_name,'New_Fba',2,0,100,19,ean,round(purch_price*2.0+3.5,2),round(purch_price,2), round(purch_price/2.0,2)] + ref_values)
                    else:
                        missing_ean.append(ean)

                else:
                    logging.warning("{0} not found ".format(sku))
            else:
                header_read = True

                if "sku" in row:
                    sku_index = row.index("sku")

                if "asin" in row:
                    asin_index = row.index("asin")

                if "product-name" in row:
                    prod_name_index = row.index("product-name")

                if sku_index < 0 or asin_index < 0 or prod_name_index < 0:
                    raise Exception("Could not find needed columns")

                writer.writerow(['sku', 'asin','product-name','Zustand', 'FPB', 'Versandkosten', 'Bestand', 'MWST', 'EAN', "VK", "EK", "EK_halb"] + headers )
        for ean in missing_ean:
            writer.writerow(['','','','','','','','','','','','','','','ERROR',ean])

def process(data_root):
    path_ref = os.path.join(data_root, "ref")
    path_in = os.path.join(data_root, "in")
    path_out = os.path.join(data_root, "out")
    path_proc = os.path.join(data_root, "processed")
    path_err = os.path.join(data_root, "error")
    path_log = os.path.join(data_root, "log")

    files = os.listdir(path_in)
    num_files = len(files)

    print("Found {0} files...".format(num_files))

    if num_files == 0:
        return

    ref_dict, headers = read_ean_lookup(path_ref)

    for f in files:
        log_file_name = time.strftime("%Y%m%d-%H%M%S") + '.log'

        in_file = os.path.join(path_in, f)
        prefix = 'dg_' if f[:3].lower() == 'dg_' else ''
        out_file_name = prefix + 'fba_artikelanlage.csv'
        out_file = os.path.join(path_out, out_file_name)
        proc_file = os.path.join(path_proc, f)
        err_file = os.path.join(path_err, f)
        log_file = os.path.join(path_log, log_file_name)

        logging.basicConfig(filename=log_file, level=logging.DEBUG)

        logging.debug("Calculating inventory for {0}...".format(in_file))

        if os.path.isfile(in_file):
            try:
                print("Converting {0} to {1}...".format(in_file, out_file))
                convert_fba(in_file, out_file, ref_dict, headers)
                shutil.move(in_file, proc_file)
            except Exception as e:
                logging.error(e)
                shutil.move(in_file, err_file)
                os.remove(out_file)


def main():
    #data_root = r"/home/holger/git/thelen/data/"
    data_root = r"/ftproot/"
    #data_root = r"c:/temp/thelen/"

    project_data_root = os.path.join(data_root, "Matching_FBA_Artikelanlage")

    process(project_data_root)

    print("Done.")


if __name__ == "__main__":
    main()


