#!/usr/bin/env python
import os
import shutil
import codecs
import csv
import logging
import locale

__author__ = 'Holger Knust'

def check_for_dupes(in_file, out_file):
    header_read = False

    stock_index = -1
    reserved_stock_index = -1

    locale.setlocale(locale.LC_ALL,'de_DE.utf8')

    with codecs.open(in_file, "r", encoding='utf-8') as f, codecs.open(out_file, "w", encoding='utf-8') as of:
        #dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
        #f.seek(0)

        reader = csv.reader(f, delimiter=';')
        writer = csv.writer(of, delimiter=';')
        for row in reader:
            if any(row):
                if header_read:
                    stock = locale.atof(row[stock_index])
                    reserved = locale.atof(row[reserved_stock_index])
                    avail_stock = int(stock-reserved)
                    row.insert(2,avail_stock)
                else:
                    header_read = True
                    stock_index = row.index('Stock')
                    reserved_stock_index = row.index('ReservedStock')
                    row.insert(2,"Availstock")

                writer.writerow(row)


def process_files(data_root):
    path_in = os.path.join(data_root, "in")
    path_out = os.path.join(data_root, "out")
    path_prc = 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

    for f in files:
        log_file_name = os.path.splitext(f)[0] + '.log'

        in_file = os.path.join(path_in, f)
        out_file = os.path.join(path_out, f)
        prc_file = os.path.join(path_prc, f)
        err_file = os.path.join(path_err, f)
        log_file = os.path.join(path_log, log_file_name)

        if os.path.isfile(in_file):
            logging.basicConfig(filename=log_file,level=logging.DEBUG)

            logging.debug("Aggregating quantities in  {0}...".format(in_file))
            try:

                check_for_dupes(in_file, out_file)
                shutil.move(in_file, prc_file)
            except Exception as e:
                logging.error(e)
                shutil.move(in_file, err_file)


def main():
    data_root = r"/ftproot/"
    #data_root = r"/data/projects/pycharm/thelen/conversion/data/"
    #data_root = r"c:/temp/thelen/"


    dupe_data_root = os.path.join(data_root, "Matching_Stock_Plenty")
    process_files(dupe_data_root)

if __name__ == "__main__":
    main()
