package com.bsis.peuplement.service;

import com.bsis.peuplement.model.Dossier;

import com.bsis.peuplement.model.Redevable;
import com.bsis.peuplement.model.ResultDossier;
import com.bsis.peuplement.repository.DossierRepository;
import com.bsis.peuplement.repository.RedevableRepository;
import com.bsis.peuplement.tasks.Tasks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class DossierService {
    @Autowired
    private DossierRepository dossierRepository;
    @Autowired
    private RedevableRepository redevableRepository;
    //...................................................................
    //                              Read
    //...................................................................
    public List<Dossier> getAll()
    {
        return dossierRepository.findAll();
    }

    //................................
    public Optional<Dossier> getById(Long id)
    {
        return  dossierRepository.findById(id);
    }
    //...................................................................
    public long count() {
        return dossierRepository.count();
    }
    //...................................................................
    //                            Update
    //...................................................................
    public Dossier update(Dossier dossier){
        return	dossierRepository.save(dossier);
    }

    //*******************************************************************
    //  One dossier Peuplement
    //*******************************************************************
    public Dossier peuplement (Dossier dossier) {
        //.............New resultDossier..................................
        ResultDossier resultDossier = new ResultDossier(); //
        //.............Get Redevable of Dossier...........................
        Long redevable_id = dossier.getRedevable_id();  // obtain the redevable
        Redevable redevable = redevableRepository.getById(redevable_id);
        //....Upadte information of resultDossier by dossier_Id & redevable_id & siretDossier.........................
        resultDossier.setDossier_id(dossier.getDossier_id());
        resultDossier.setRedevable_id(redevable_id);
        resultDossier.setSiretRedevable(redevable.getCode_siret());
        //.......Read the address...............
        if (dossier.getAdresse()==null)
        {
           resultDossier.setDossierState("Err Adresse");
        }
        else
        {
            //........ Calcul XY StoAdr
           String [] xyStorAdr= Tasks.crdnXYLambert93StorAdr(dossier.getAdresse());
           if (xyStorAdr[0]=="-111111111111111")
           {
             resultDossier.setAdresse(dossier.getAdresse());
             resultDossier.setDossierState("Err xyStorAdr Address not found");
           }
           else
           {
               resultDossier.setxStorAdr(xyStorAdr[0]);
               resultDossier.setyStorAdr(xyStorAdr[1]);
               //........ Calcul XY Redevable platFile
               if(redevable.getCode_siret()==null)
               {
                  resultDossier.setDossierState("Err SIRET redevable not found");
               }
               else
               {
                   resultDossier.setSiretRedevable(redevable.getCode_siret());
                   String [] xyPlatFile= Tasks.crdnXYLambert93FichierPlat(redevable.getCode_siret());
                  if(xyPlatFile[0]=="-99999999999999999")
                  {
                      resultDossier.setDossierState("Err XY flatFile not found");
                  }
                  else
                  {
                    resultDossier.setxFlatFile(xyPlatFile[0]);
                    resultDossier.setyFlatFile(xyPlatFile[1]);
                    resultDossier.setDistance(""+Tasks.calculateDistance(Long.parseLong(xyStorAdr[0]),
                                                                         Long.parseLong(xyStorAdr[1]),
                                                                         Long.parseLong(xyPlatFile[0]),
                                                                         Long.parseLong(xyPlatFile[1])));
                   // decision()
                  }
               }
           }
        }





        return dossier;
    }
 /*




    //...................................................................
    //                          RECHERCHE
    //...................................................................
    public String[] xyStorAdr(Dossier dossier) {

        String adresse = dossier.getAdresse();
        if (adresse == null) {adresse ="null";}

        String [] xy= Tasks.crdnXYLambert93StorAdr(adresse,storAdr);
        return xy;
    }
    //...................................................................
    // Distance Between p1(X1 Y1) & p2(X2 Y2)
    //...................................................................
    public double distance(String x1, String y1, String x2, String y2 )
    {
        return Tasks.calculateDistance(Double.parseDouble(x1),Double.parseDouble(y1),Double.parseDouble(x2),Double.parseDouble(y2));
    }
    //.................................................................................
    // Peuplement one dossier --> Update Dossier(dossierId) DossierDistance(dossierId)
    //..................................................................................
    public DossierDistance peuplementById (String dossierId) {
        Dossier dossier = getByDossierId(dossierId);
        DossierDistance dossierDistance = new DossierDistance();
        dossierDistance.setDossierId(dossierId);
        dossierDistance.setRedevableId(dossier.getRedevableId());
        dossierDistance.setSiretRedevable(redevableService.getByRedevableId(dossier.getRedevableId()).getCodeSiret());
        if (dossier.getAdresse() == null)
        {
            dossierDistance.setDossierState("Err Adresse dossier");
            dossierDistanceRepository.save(dossierDistance);
        }
        else
        {
           dossierDistance.setAdresse(dossier.getAdresse());
           String[] point1 = xyStorAdr(dossier);
           if (point1[0] == "-111111111111111")
           {
               dossierDistance.setDossierState("Err xyStorAdr not found");
           }
           else
           {
              dossierDistance.setxStorAdr(point1[0]);
              dossierDistance.setyStorAdr(point1[1]);
              String siret = "---";
              String[] point2 = redevableService.xyFichierPlat(dossier, siret);
              if (siret == "")
              {
                  dossierDistance.setDossierState("Err siretRedevable not found");
              }
              else
              {
                  if (siret == "00000000000000")
                  {
                      dossierDistance.setDossierState("Err siret null");
                  }
                  else
                  {
                      if (point2[0] == "-99999999999999999")
                      {
                         dossierDistance.setDossierState("Err xyFlatFile not found");
                      }
                      else
                      {
                          dossierDistance.setDossierState("OK");
                          dossierDistance.setSiretDossier(dossierDistance.getSiretRedevable());
                          dossierDistance.setxFlatFile(point2[0]);
                          dossierDistance.setyFlatFile(point2[1]);
                          dossierDistance.setDistance("" + distance(point1[0], point1[1], point2[0], point2[1]));
                          dossier.setSiret(dossierDistance.getSiretRedevable());
                      }
                  }
              }
           }
           dossierDistance.setDossierId(dossier.getDossierId());
           dossierDistanceRepository.save(dossierDistance);
           dossierRepository.save(dossier);
          // System.out.println(dossierDistance);
        }
        return dossierDistance;
    }
    //........................................................
    // All distance --> create of dossierDistance list
    //........................................................
    public List<DossierDistance> peuplementAll()
    {
        List<DossierDistance> dossierDistances = new ArrayList<>();
        // create a new logFile
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
        String formattedDateTime = currentDateTime.format(formatter);

        String logFile=log+formattedDateTime+".csv";
        List<Dossier> dossiers = getAll();  // recuperer tous les dossier
        Long cpt = 1L;
        Long total = dossierRepository.count();

        //*********************************************************************************************
        try {
            System.out.println(logFile);
            FileWriter fileWriter = new FileWriter(logFile, false);
            fileWriter.write("");
            writeToFile(logFile,"dossierState;dossierId;adresse;siretDossier;xStorAdr;yStorAdr;redevableId;siretRedevable;xFlatFile;yFlatFile;distance\n");
            for (Dossier dossier:dossiers )
            {
                DossierDistance dossierDistance = peuplementById(dossier.getDossierId());
                writeToFile(logFile,dossierDistance.getDossierState()+";"+dossierDistance.getDossierId()+";"+dossierDistance.getAdresse()+";"+dossierDistance.getSiretDossier()+";"+dossierDistance.getxStorAdr()+";"+dossierDistance.getyStorAdr()+";"+dossierDistance.getRedevableId()+";"+dossierDistance.getSiretRedevable()+";"+dossierDistance.getxFlatFile()+";"+dossierDistance.getyFlatFile()+";"+dossierDistance.getDistance()+"\n");
//              writeToFile(logFile,"-;-;-;-;-;-;-;-;-;-;-\n");
                System.out.println(dossierDistance);
                System.out.println("["+cpt+"/"+total+" dossiers]");

                cpt++;
            }
        } catch (IOException e) {
            System.out.println("Error while writting log file : " + logFile);
            e.printStackTrace();
        }
        return dossierDistances;
    }
   //..........................................................
    public static void writeToFile(String logFile, String content) throws IOException {
        try (FileWriter fileWriter = new FileWriter(logFile, true)) {
            fileWriter.write(content);
        }
    }
    //............................................................
    public List<DossierDistance>  peuplementSet(String set)
    {
        String path="/"+set;
        List<DossierDistance> dossierDistances = new ArrayList<>();
        List<String> dossierIds = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(path)))
        {
            String ligne;
            while ((ligne = reader.readLine()) != null)
            {
                String[] valeurs = ligne.split(";");
                for (String valeur: valeurs)
                {
                    dossierIds.add(valeur);
                }
            }
        }
        catch (IOException e)
        {
            System.out.println("File not found");
            e.printStackTrace();
        }
        for (String dossierId:dossierIds)
        {
            DossierDistance dossierDistance=peuplementById(dossierId);
            dossierDistances.add(dossierDistance);
            dossierDistanceRepository.save(dossierDistance);
        }
        return dossierDistances;
    }

    // ............................................................
    public String init ()
    {

//        String stringUrl ="http://10.18.126.211:22/";
//        try {
//            URL url = new URL(stringUrl);
//
//            // Obtention du chemin du fichier à partir de l'URL
//            String filePath = url.getPath()+"/s25_savoi_jboss/logs/sav.txt";
//            File file = new File(filePath);
//            //***********************
//            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
//                String line;
//
//                // Lecture ligne par ligne et affichage
//                while ((line = reader.readLine()) != null) {
//                    System.out.println(line);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            //************************
//
//            System.out.println("Chemin du fichier : " + file.getAbsolutePath());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }




        List<Dossier> dossiers = dossierRepository.findAll();
        for (Dossier dossier: dossiers)
        {
            dossier.setSiret("");
            dossierRepository.save(dossier);
        }
        dossierDistanceRepository.deleteAll();
        return "Init process completed successfully";
    }

    public String FlatFileFiltrer() {
       String inputFile= String.valueOf(getClass().getClassLoader().getResource("GeolocalisationEtablissement_Sirene_pour_etudes_statistiques_utf8.csv"));
       String outputFile= String.valueOf(getClass().getClassLoader().getResource("FilteredFile1.csv"));
       Tasks.filtred(inputFile, outputFile);
        return "OK";
    }*/
}

