package com.bsis.peuplement.tasks;

import com.bsis.peuplement.model.SiretXY;
import com.bsis.peuplement.parametres.Parametres;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Tasks
{
//   public static String path ="";
    //...........................................................................
    // Filtrer le fichier plat
    //...........................................................................
     public static void filtred(String inputFile, String outputFile)
     {
//         URL resourceUrl = getClass().getClassLoader().getResource("log.txt");
//         String inputFile=this.path+"GeolocalisationEtablissement_Sirene_pour_etudes_statistiques_utf8.csv";
//         String outputFile=this.path+"FilteredFile1.csv";
         String filterColumn = "plg_code_commune";
         int minValue = 75000;
         int maxValue = 75999;

         try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
              FileWriter writer = new FileWriter(outputFile)) {

             String line;
             while ((line = reader.readLine()) != null)
             {
                 String[] fields = line.split(";");
                 String value = fields[10];
                 if (isNumeric(value) && isBetween(Integer.parseInt(value), minValue, maxValue))
                 {
                     line=fields[0]+";"+fields[1]+";"+fields[2]; // pour eliminer les champs Inutils
                     writer.write(line + "\n");
                 }
             }
             System.out.println("Le fichier a été filtré avec succès !");
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     private static boolean isNumeric(String str) {
        return str.matches("-?\\d+");
    }
    private static boolean isBetween(int value, int min, int max) {
        return value >= min && value <= max;
    }

    //...........................................................................
    // Les coordonnées XY d'une adresse de dossier sur storAdr
    //...........................................................................
    public static String [] crdnXYLambert93StorAdr(String adresse)
    {

        //Tasks.filtred();
//        System.out.println("(Address).........> "+adresse);

//        String fileStorAdr= path+"storAdr2.csv";
        String[] resultXY = new String[2];
        resultXY[0]="-111111111111111";
        resultXY[1]="-111111111111111";
        Boolean tr = false;
        try (BufferedReader reader = new BufferedReader(new FileReader(Parametres.storAdr))) {
            String ligne;
            int indexAdresse = 0;
            int indexX = 1;
            int indexY = 2;
            ligne = reader.readLine();
            while (!tr && ((ligne = reader.readLine()) != null))
            {
                String[] valeurs = ligne.split(";");
                //................................................
                int nbIndicesDepart = valeurs[0].length()-adresse.length()+1;
                for (int i = 0; i<nbIndicesDepart; i++)
                if(valeurs[0].substring(i, i+adresse.length()).equalsIgnoreCase(adresse))
                {
                    resultXY[0]=valeurs[1];
                    resultXY[1]=valeurs[2];
                    tr = true;
                    break;
                }
            }

        } catch (IOException e) {
            System.out.println("StorAdr File not found");
            e.printStackTrace();
        }

        return resultXY;
    }
    //...........................................................................
    // Les coordonnées XY de SIRET redevable sur le fichier plat
    //...........................................................................
    public static String [] crdnXYLambert93FichierPlat(String siret)
    {
        String siretForSearching =  siret.replaceAll("\\s+", ""); // blanc elimination
        //System.out.println("(SIRET).........> "+siret);
       // String platFile="FilteredFile.csv";
        String[] resultXY = new String[2];
        resultXY[0]="-99999999999999999";
        resultXY[1]="-99999999999999999";
        Boolean tr = false;
        try (BufferedReader reader = new BufferedReader(new FileReader(Parametres.platFile)))
        {
            String ligne;
            int indexSiret = 0;
            int indexX = 1;
            int indexY = 2;
            ligne = reader.readLine();

            while (!tr && ((ligne = reader.readLine()) != null))
            {
                String[] valeurs = ligne.split(";");

                if(valeurs[0].startsWith(siretForSearching))   // in the flatFile is siret(14) but we search siren(9)
                {
                    resultXY[0]=valeurs[1];
                    resultXY[1]=valeurs[2];
                    tr = true;
                    break;
                }

            }
        }
        catch (IOException e) {
            System.out.println("PlatFile not found");
            e.printStackTrace();
        }
        return resultXY;
    }

    //...........................................................................
    //  Calcul de la distance
    //............................................................................

    public static double calculateDistance(double x1, double y1, double x2, double y2) {
        double distanceX = x2 - x1;
        double distanceY = y2 - y1;
        double distanceSquared = distanceX * distanceX + distanceY * distanceY;
        double distance = Math.sqrt(distanceSquared);
        return distance;
    }

    //............................................................................
    // getSiretWithSiren
    //............................................................................
    public  List<SiretXY> getSiretAccordingSiren(String siren)
    {
//        String flatFile= path+"FilteredFile.csv";
        List<SiretXY> siretXYs =  new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(Parametres.platFile))) {
            String ligne;
            int indexSiret = 0;
            int indexX = 1;
            int indexY = 2;
            while ((ligne = reader.readLine()) != null)
            {
                String[] valeurs = ligne.split(";");
                //  System.out.println(valeurs[indexSiret].substring(valeurs[0].length() - 9));
                if (valeurs[indexSiret].startsWith(siren))
                {
                    SiretXY siret = new SiretXY();
                    siret.setSiret(valeurs[indexSiret]);
                    siret.setX(valeurs[indexX]);
                    siret.setY(valeurs[indexY]);
                    siretXYs.add(siret);
                }
            }

        } catch (IOException e)
        {
            System.out.println("Filtred File not found");
            e.printStackTrace();
        }
        return siretXYs;
    }

}
