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

__author__ = 'Holger Knust'

def check_for_dupes(in_file, out_file):
    header_read = False

    material_index = -1

    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, dialect)
        writer = csv.writer(of, delimiter=';')
        for row in reader:
            if any(row):
                if header_read:
                    current_term = row[material_index]
                    if current_term == "Textil / Synthesefaser_Polyester" or current_term == "" or current_term == "<p>&nbsp;</p><p>&nbsp;</p>" \
                        or current_term == "<p>Textil / Synthesefaser_Polyester</p>":
                        row[material_index] = "37% Baumwolle/36% Polyacryl/17% Polyamid/6% Polyester/4% Elastodien"
                else:
                    header_read = True
                    material_index = row.index("ItemTextTechnicalData")
                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("Substituting materials 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_Textilkennzeichnung")
    process_files(dupe_data_root)

if __name__ == "__main__":
    main()
