#!/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
    ean_index = -1
    ean_set = set()
    dupes_found = False

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

        reader = csv.reader(f, dialect)
        writer = csv.writer(of, delimiter=';')
        for row in reader:
            if any(row):
                if header_read:
                    if row[ean_index] in ean_set:
                        # write row with duplicate EAN to output file
                        writer.writerow(row)
                        logging.info("Duplicate of {0} found!".format(row[ean_index]))
                        dupes_found = True
                    else:
                        ean_set.add(row[ean_index])
                else:
                    header_read = True
                    if 'EAN' in row:
                        ean_index = row.index('EAN')
                    if 'ns1:EAN' in row:
                        ean_index = row.index('ns1:EAN')
                    
    if not dupes_found:
        # delete empty dupes file
        os.remove(out_file)
        logging.debug("No duplicates found.")

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("Checking {0} for duplicates.".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/"

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

if __name__ == "__main__":
    main()
