package com.alexanderlogistics.migration;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.imixs.melman.FormAuthenticator;
import org.imixs.melman.WorkflowClient;
import org.imixs.workflow.ItemCollection;
import org.imixs.workflow.datev.imports.DatevImportAdapter;
import org.imixs.workflow.exceptions.PluginException;
import org.junit.Before;
import org.junit.Test;

import junit.framework.Assert;

public class DueDateBugfix {

    WorkflowClient workflowCLient = null;
    String user = "archive";
    String ps = "archive4imixs";
    String restAPI = "https://alexander-logistics.office-workflow.de/api";

    @Before
    public void setup() throws PluginException {
        // Init Workflow Client
        workflowCLient = new WorkflowClient(restAPI);
        FormAuthenticator formAuth = new FormAuthenticator(restAPI, user, ps);
        workflowCLient.registerClientRequestFilter(formAuth);

    }

    /**
     * Diese Test Method wandelt die Datei OPD_migration_230126.csv in eine EXTV
     * Datev Datei um, welche wir dann für einen einmaligen Import der
     * Rechnugnsdaten verwenden können.
     * 
     */
    @Test
    public void fixe() {

        System.out.println("***********************");
        System.out.println("* Bugfix *");
        System.out.println("***********************");
        
        /* Erledigte
         * 
         * 
         * EXTF_202301_202302030602_1295
         * EXTF_202301_202302060601_1296
         * EXTF_202301_202302070603_1297
         * EXTF_202301_202302080603_1298
         * EXTF_202301_202302090604_1299
         * EXTF_202301_202302100603_1300
         * EXTF_202301_202302130601_1301
         * EXTF_202301_202302140604_1302
         * EXTF_202301_202302141840_1303
         * EXTF_202301_202302160944_1304
         * EXTF_202302_202302020601_1294
         * EXTF_202302_202302030602_1295
         * EXTF_202302_202302060601_1296
         * EXTF_202302_202302070603_1297
         * EXTF_202302_202302080603_1298
         * EXTF_202302_202302090604_1299
         * EXTF_202302_202302100604_1300
         * EXTF_202302_202302130601_1301
         * EXTF_202302_202302140604_1302
         * EXTF_202302_202302141840_1303
         * EXTF_202302_202302160944_1304
         * EXTF_202303_202302070603_1297
         * EXTF_202303_202302080603_1298
         * EXTF_202303_202302090604_1299
         * EXTF_202303_202302100603_1300
         * EXTF_202303_202302130601_1301
         * EXTF_202303_202302140604_1302
         * EXTF_202303_202302141840_1303
         * EXTF_202303_202302160944_1304
         * 
         */

        int count = 0;
        int fixes = 0;
        String filename_input = "datev/duedate-bug/EXTF_202303_202302160944_1304.csv";
        FileInputStream fis;
        BufferedReader br = null;
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            File inputFile = new File(classLoader.getResource(filename_input).getFile());
            Assert.assertTrue(inputFile.exists());
            fis = new FileInputStream(inputFile);
            DataInputStream in = new DataInputStream(fis);
            br = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));

            // read the first 2 line containing the field names
            String fieldnames = br.readLine();
            fieldnames = br.readLine();

            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");

            // Jetzt iterieren wir über die Input Datei und schreiben jeweilse eine Zeile
            // in die Output Datei...
            String line;

            while ((line = br.readLine()) != null) {

                String[] data = line.split(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)", 999);

                Date dueDate = new Date();
                String belegNummer = DatevImportAdapter.csvVal(data[10]);
                try {
                    dueDate = dateFormatter.parse(DatevImportAdapter.csvVal(data[23]));

                    // suche Rechnung
                    String query = "$modelversion:\"rechnungsausgang-de-1.0\" AND type:workitem AND invoice.number:\""
                            + belegNummer+"\"";

                    workflowCLient.setPageSize(1);
                    List<ItemCollection> invoices = workflowCLient.searchDocuments(query);
                    
                    if (invoices.size()==1) {
                        ItemCollection invoice=invoices.get(0);
                        
                        Date bugDate = invoice.getItemValueDate("invoice.duedate");
                       
                        
                        if (!dueDate.equals(bugDate)) {
                            fixes++;
                            System.out.println(".... FIX " + belegNummer + " -> " + dueDate  + " Bugi Date="+bugDate);
                            
                            
                            invoice.setItemValue("invoice.duedate", dueDate);
                            invoice.setItemValue("invoice.reminder", dueDate);
                            
                            if (invoice.getTaskID()==5100) {
                                invoice.event(20);
                                workflowCLient.processWorkitem(invoice);
                                
                            } else {
                                workflowCLient.saveDocument(invoice);  
                            }
                            
                        } else {
                            System.out.println("....  OK " + belegNummer + " -> " + dueDate  + " Bugi Date="+bugDate);
                        }
                        
                    } else {
                        System.out.println(".... " + belegNummer + " ist unbekannt");
                    }

                   
                } catch (Exception e) {
                    System.out.println("hat nicht geklappt: "+e.getMessage());
                }
                count++;
                
              //if (fixes>0) break;

            }

            System.out.println("... fininshed - read " + count + " lines -" + fixes + " fixes :-)");

        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Assert.fail();
                }
            }
        }
    }

}
