#!/usr/bin/env python

import os
import codecs
import csv

__author__ = 'Holger Knust'

inv_dict = dict()


def write_summary(out_file, warehouse_id):
    with codecs.open(out_file, "w", encoding='utf-8') as of:
        writer = csv.writer(of, delimiter=";")

        if len(inv_dict):
            writer.writerow(["ean", "stock", "storehouse_id", "PurchasePrice"])
            for ean, t in inv_dict.items():
                writer.writerow([ean, t[0], warehouse_id, t[1]])


def summarize(in_file):
    header_read = False
    ean_index = -1
    inv_index = -1
    purchase_price_index = -1

    with codecs.open(in_file, "r", encoding='utf-8') as f:
        reader = csv.reader(f, delimiter=";")

        for row in reader:
            if header_read:
                ean = row[ean_index]
                price = row[purchase_price_index]

                if len(ean.strip()) == 0:
                    continue

                inv_text = row[inv_index]

                try:
                    in_stock = int(inv_text)
                except ValueError:
                    in_stock = 0

                if ean in inv_dict:
                    current_stock = inv_dict[ean][0] + in_stock
                    inv_dict[ean] = (current_stock, price)
                else:
                    inv_dict[ean] = (in_stock, price)
            else:
                header_read = True

                if 'ean' in row:
                    ean_index = row.index('ean')
                if 'stock' in row:
                    inv_index = row.index('stock')
                if 'PurchasePrice' in row:
                    purchase_price_index = row.index('PurchasePrice')

                if ean_index < 0 or purchase_price_index < 0:
                    raise Exception("Not all necessary columns found")


def process_files(data_root, in_folder, out_folder, prefix, warehouse_id):
    path_in = os.path.join(data_root, in_folder)
    path_out = os.path.join(data_root, out_folder)

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

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

    if num_files == 0:
        return

    for f in files:
        in_file = os.path.join(path_in, f)
        out_file = os.path.join(path_out, prefix + "_Gesamt.csv")

        if os.path.isfile(in_file):
            try:
                summarize(in_file)
                write_summary(out_file, warehouse_id)
            except Exception as e:
                print(e)

def main():
    global inv_dict

    data_root = r"/ftproot/"
    # data_root = r"/home/holger/git/thelen/data/"

    inv_data_root = os.path.join(data_root, "SSW_Exporte/Bestand_SSW/inventory")
    process_files(inv_data_root, "FBA", "HK_FBA", "FBA", 33)
    inv_dict = dict()
    process_files(inv_data_root, "LAGER_9", "HK_LAGER_9", "LAGER9", 9)
    inv_dict = dict()
    process_files(inv_data_root, "LAGER_12", "HK_LAGER_12", "LAGER12", 12)
    inv_dict = dict()
    process_files(inv_data_root, "SSW_BESTAND", "HK_SSW_BESTAND", "SSW_BESTAND", 11)


if __name__ == "__main__":
    main()

