#!/usr/bin/env python

__author__ = 'holger'

import csv
import codecs
from datetime import datetime
import locale
import logging
import os
import shutil
import time

# ItemVariationNo;RowQuantity;RowOrderID
COL_IN_ITEM_NO = 0
COL_IN_QTY = 1
COL_IN_ORDER_ID = 2

ERROR_OCCURRED = "***ERROR"

def create_order_files(in_file, out_file, out_file2):
    with codecs.open(in_file, "r", encoding='cp1252') as f, \
            codecs.open(out_file, "w", encoding='cp1252') as of, \
            codecs.open(out_file2, "w", encoding='cp1252') as ofp:
        reader = csv.reader(f, delimiter=';')
        writer = csv.writer(of, delimiter=';')
        writer_plenty = csv.writer(ofp, delimiter=';')

        # Write header for Plenty output
        writer_plenty.writerow(['OrderID', 'Marking', 'OrderStatus', 'CustomerInfo'])

        # Get locale
        #locale.setlocale(locale.LC_TIME, 'de_DE.utf8')
        locale.setlocale(locale.LC_ALL,'de_DE.utf8')
        # and create a date/time template for output
        date_format = locale.nl_langinfo(locale.D_T_FMT)
        header_read = False

        for row in reader:
            if len(row) != 3:
                logging.error("Input row does not have 3 columns. Number of columns found: " + str(len(row)))
                raise Exception()

            if not header_read:
                header_read = True
                continue

            item_num = str(row[COL_IN_ITEM_NO])
            quantity = locale.atof(row[COL_IN_QTY])
            order_id = str(row[COL_IN_ORDER_ID])

            item_num_components = item_num.split('#')

            if len(item_num_components) == 2:
                # Write row to regular output file
                writer.writerow([item_num_components[0], item_num_components[1], str(int(quantity))])
                # Write row to plenty output file
                writer_plenty.writerow([order_id, 10, 4.1, datetime.now().strftime(date_format)])
            else:
                writer_plenty.writerow([order_id, ERROR_OCCURRED, '', ''])


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)

    if num_files == 0:
        return

    # Set up logging
    datetime_file_name = time.strftime("%Y%m%d-%H%M%S")
    log_file_name = datetime_file_name + '.log'
    log_file = os.path.join(path_log, log_file_name)
    logging.basicConfig(filename=log_file, level=logging.DEBUG)

    logging.info("Found {0} files...".format(num_files))

    for f in files:
        in_file = os.path.join(path_in, f)
        proc_file = os.path.join(path_prc, f)
        err_file = os.path.join(path_err, f)

        # Get the file name
        in_file_name = os.path.split(in_file)[1]
        in_file_base = os.path.splitext(in_file_name)[0]
        in_file_ext = os.path.splitext(in_file_name)[1]
        out_file_name = in_file_name
        out_file_name2 = in_file_base + '_plenty' + in_file_ext

        out_file = os.path.join(path_out, out_file_name)
        out_file2 = os.path.join(path_out, out_file_name2)

        if os.path.isfile(in_file):
            try:
                logging.debug("Processing {0}...".format(in_file))
                create_order_files(in_file, out_file, out_file2)
                if os.path.isfile(in_file):
                    shutil.move(in_file, proc_file)
            except Exception as e:
                logging.error(e)

                # Move in file to error
                shutil.move(in_file, err_file)

                # Clean up. Remove broken out files if they exist
                if os.path.isfile(out_file):
                    os.remove(out_file)
                if os.path.isfile(out_file2):
                    os.remove(out_file2)

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

    data_root = os.path.join(data_root, "Matching_Jako_Bestellung")
    process_files(data_root)

if __name__ == "__main__":
    main()
