/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.Traitement;


import com.ibm.icu.text.RuleBasedNumberFormat;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import javafx.collections.ObservableList;

/**
 * @author Maher Ben Tili
 */
public class Adaptateur {
    
    public static String addSlashes(String s) {
        s = s.replaceAll("\\\\", "\\\\\\\\");
        s = s.replaceAll("\\n", "\\\\n");
        s = s.replaceAll("\\r", "\\\\r");
        s = s.replaceAll("\\00", "\\\\0");
        s = s.replaceAll("'", "''");
        return s;
    }
    
    //yyyy/MM/dd HH:mm:ss
    //yyyy
    public static String getDefaultCurrentDate(String Format){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Format);  
        LocalDateTime now = LocalDateTime.now();  
        return dtf.format(now);
    }
    
    public static String NormalDateFormat(LocalDate date){
        if(date != null){
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            return formatter.format(date);  //  23/06/2015   
        }else{
            return null;
        }
    }
    
    public static String DatabaseDateLocalDate(LocalDate date){
        if(date != null){
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return formatter.format(date);  //  2015-06-23  
        }else{
            return null;
        }
    }
    
    
    
    
    public static LocalDate  StringToLocalDate(String date){
        
        //  date = "2016-08-16"
        if(date != null){
            LocalDate localDate = LocalDate.parse(date);
            return localDate;
        }else{
            return null;
        }
    }
    
    //2003-01-30   =>  30/01/2003
    public static String NormalDateFormat(String date){
        if(date != null){
            String jour= date.substring(8, 10);
            String mois=date.substring(5, 7);
            String annee=date.substring(0, 4);
            String dateconf = jour+"/"+mois+"/"+annee;
            return dateconf;      
        }else{
            return null;     
        }
    }
    
    
    //2003-01-30 10:30:22  =>  30/01/2003 10:30
    public static String NormalDateTimeFormat(String date){
        if(date != null){
            String jour= date.substring(8, 10);
            String mois=date.substring(5, 7);
            String annee=date.substring(0, 4);
            String heur = date.substring(11, 13);
            String minute = date.substring(14, 16);
            String dateconf = jour+"/"+mois+"/"+annee+" "+heur+":"+minute;
            return dateconf;      
        }else{
            return null;     
        }
    }
    
    
    public static String DatabaseDateFormat(String date){
        //  23/06/2015   
        String jour= date.substring(0, 2);
        String mois=date.substring(3, 5);
        String annee=date.substring(6, 10);
        String dateconf = annee+"-"+mois+"-"+jour;
        return dateconf;
    }
    
    
    
    public static float StringToFloat(String ch)
    {
        float reel = 0;
        if(!ch.isEmpty()){
            try{
                reel =Float.parseFloat(ch.replace(',','.'));
            }
            catch(NumberFormatException nfe){
                reel = 0 ;
            }
        }
        return reel ;   
    }
    
    
    // 14.0 =>  14
    public static String StringDeleZero(String ch){
        try{
            DecimalFormat df = new DecimalFormat("#.###");
            if(ch.isEmpty())
                return ch ;
            else{
                double d = Double.valueOf(ch.replace(',','.'));
                return df.format(d);
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+ch+"\n Method: Adaptateur.StringDeleZero \n"+nfe.getMessage()+" \n");
            return ch ;
        }
        catch(IllegalArgumentException string){
            System.out.println("erreur Value: "+ch+"\n Method: Adaptateur.StringDeleZero \n"+string.getMessage()+" /n");
            return ch ;
        }
    }
    
    //2100.25   ===> 2 100,25
    public static String StringToStringEspace(String ch)
    {
        if(!new contro().isStringNull(ch)){
            float f = StringToFloat(ch);
            try{
                DecimalFormat Formatter = new DecimalFormat("##,###.## ");
                return Formatter.format(f);
            }
            catch(NumberFormatException nfe){
                System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.StringToStringEspace    \n"+nfe.getMessage()+" \n");
                    return String.valueOf(f) ;
            }
        }
        return "0";
    }
    
    //2100.25   ===> 2 100,25 DT
    public static String StringToStringEspaceCurrency(String ch){
        float f = StringToFloat(ch);
        try{
            DecimalFormat Formatter = new DecimalFormat("##,###.## ");
            return Formatter.format(f)+" "+ParametreSystem.CurrencySign;
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.StringToStringEspaceCurrency    \n"+nfe.getMessage()+" \n");
            return String.valueOf(f) ;
        }
    }
    
    
    public static String floatDeleZero(float f)
    {
        try{
            DecimalFormat df = new DecimalFormat("#.###");
            return df.format(f);
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n Method: Adaptateur.floatDeleZero \n"+nfe.getMessage()+" \n");
            return String.valueOf(f) ;
        }
    }
    
    
    //5.654201458 =>  5.654         5.654971458 => 5.655
    public static String ArrondStringToString(String ch){
        try{
            DecimalFormat df = new DecimalFormat("0.000");
            if(ch.isEmpty())
                return "0";
            else{
                df.setMaximumFractionDigits(3);
                
                double d = Double.valueOf(ch.replace(',','.'));
                String x = df.format(d).replaceAll(",000","");
                
                if(d==0)
                    return "0";
                else
                    return x;
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+ch+"\n  Method: Adaptateur.ArrondStringToString  \n"+nfe.getMessage()+" \n");
            return ch ;
        }
        catch(IllegalArgumentException string){
            System.out.println("erreur Value: "+ch+"\n   Method: Adaptateur.ArrondStringToString   \n"+string.getMessage()+" \n");
            return ch ;
        }
    } 
    
    public static float ArrondStringToFloat(String ch){
        try{
            if(ch.isEmpty())
                return 0;
            else{
                DecimalFormat df = new DecimalFormat("0.000");
                df.setMaximumFractionDigits(3);
                double d = Double.valueOf(ch.replace(',','.'));
                String x = df.format(d);
                return StringToFloat(x);
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+ch+"\n   Method: Adaptateur.ArrondStringToFloat   \n"+nfe.getMessage()+" \n");
                return 0 ;
        }
        catch(IllegalArgumentException string){
            System.out.println("erreur Value: "+ch+"\n    Method: Adaptateur.ArrondStringToFloat    \n"+string.getMessage()+" \n");
                return 0 ;
        }
    }
    
    
    
    public static float ArrondFloatToFloat(float f){
        DecimalFormat df = new DecimalFormat("0.000");
        df.setMaximumFractionDigits(3);
        String ch = df.format(f);
        try{
            return Float.parseFloat(ch.replace(',','.'));
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+ch+"\n    Method: Adaptateur.ArrondFloatToFloat    \n"+nfe.getMessage()+" \n");
            return 0 ;
        }
    }
    
    
    //5.654201458 =>  5.654
    public static String ArrondFloatToStringOrigin(float f){
        try{
            DecimalFormat df = new DecimalFormat("0.000");
            df.setMaximumFractionDigits(3);
            if(f==0)
                return "0";
            else{
                String ch = df.format(f).replace(",000", "");
                return ch.replace(",", ".");
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.ArrondFloatToString    \n"+nfe.getMessage()+" \n");
            return String.valueOf(f) ;
        }
    }
    
    //5.654201458 =>  5,654
    public static String ArrondFloatToString(float f){
        try{
            DecimalFormat df = new DecimalFormat("0.000");
            df.setMaximumFractionDigits(3);
            if(f==0)
                return "0";
            else{
                String ch = df.format(f);
                return ch.replace(",000", "");
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.ArrondFloatToString    \n"+nfe.getMessage()+" \n");
            return String.valueOf(f) ;
        }

    }
    
    //2100.25   ===> 2 100,25 DT
    public static String FloatToStringEspaceCurrency(float f){
        try{
            DecimalFormat Formatter = new DecimalFormat("##,###.## ");
            return Formatter.format(f)+" "+ParametreSystem.CurrencySign;
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.ArrondFloatToString    \n"+nfe.getMessage()+" \n");
                return String.valueOf(f) ;
        }
    }
    
    //2100.25   ===> 2 100,25
    public static String FloatToStringEspace(float f){
        try{
            DecimalFormat Formatter = new DecimalFormat("##,###.## ");
            return Formatter.format(f);
        }
        catch(NumberFormatException nfe){
            System.out.println("erreur Value: "+f+"\n    Method: Adaptateur.ArrondFloatToString    \n"+nfe.getMessage()+" \n");
                return String.valueOf(f) ;
        }
    }
    
    
    
    
    //Ex 100.25   ===> 100
    public static Integer Diviseur(float value){
        
        String f1Str = Float.toString((float) value); 
        int Pos = f1Str.indexOf('.');
        if(Pos>-1){
            f1Str = f1Str.substring(0, Pos);
        }
        Integer div = Integer.parseInt(f1Str);
        return div;
    }
    
    //Ex   15.5  ==> 0.5
    public static float Modulo(float value){
        DecimalFormat df = new DecimalFormat("########.000"); 
        String str = df.format(value); 
        
        float mode = 0;
        
        if(str.indexOf(',')>-1){
            int posisition =str.indexOf(',');
            String str1 = "0"+str.substring(posisition, str.length());
            mode = Float.parseFloat(str1.replace(',', '.'));
        }
        return mode;
    }
    
    
    public static String ChiffreToLettre(BigDecimal num)
    {
        DecimalFormat DFORMAT = new DecimalFormat("###0.00");
        RuleBasedNumberFormat FORMATTER = new RuleBasedNumberFormat(RuleBasedNumberFormat.SPELLOUT);
        
        String[] s = DFORMAT.format(num).split(Pattern.quote(String.valueOf(DFORMAT.getDecimalFormatSymbols().getDecimalSeparator())));
        
        BigInteger intPart = new BigInteger(s[0]);
        BigInteger decPart = new BigInteger(s[1]);
        
        if ( s[1].equals("00") ) {
            return FORMATTER.format(intPart)+ " "+ParametreSystem.CurrencyName;
	}
	else {
            return FORMATTER.format(intPart)
                    + " "
                    + ParametreSystem.CurrencyName
                    + (intPart.intValue()>1?"s":"")
                    + " et " 
                    + FORMATTER.format(decPart)
                    + " " + ParametreSystem.CurrencyThousandth
                    + (decPart.intValue()>1?"s":"");
	}
    }
    
    
    public static <T> List<T> getUniqueRandomObjectList(ObservableList<T> list, int count) 
    {
        List<T> tempList = new ArrayList<>(list);
        Collections.shuffle(tempList);
        return tempList.subList(0, count);
    }
    
    public static <T> T getRandomObject(ObservableList<T> list) 
    {
        Random random = new Random();
        int randomIndex = random.nextInt(list.size());
        return list.get(randomIndex);
    }
    
    public static int getRandomValueBetween(int min, int max) 
    {
        Random random = new Random();
        return random.nextInt((max - min) + 1) + min;
    }
    
    public static LocalDate getRandomDateBetween(LocalDate minDate, LocalDate maxDate) {
        long daysBetween = ChronoUnit.DAYS.between(minDate, maxDate);
        long randomDays = ThreadLocalRandom.current().nextLong(daysBetween + 1);
        return minDate.plusDays(randomDays);
    }
    
    public static String getRandomTimeBetween(LocalTime minTime, LocalTime maxTime) {
        long minSeconds = minTime.toSecondOfDay();
        long maxSeconds = maxTime.toSecondOfDay();
        long randomSeconds = ThreadLocalRandom.current().nextLong(minSeconds, maxSeconds);

        LocalTime randomTime = LocalTime.ofSecondOfDay(randomSeconds);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

        return randomTime.format(formatter);
    }
    
    public static int[] generateUniqueRandomArray(int size, int maxValue) 
    {
        Random random = new Random();
        Set<Integer> uniqueValues = new HashSet<>();

        while (uniqueValues.size() < size) {
            int randomValue = random.nextInt(maxValue + 1);
            uniqueValues.add(randomValue);
        }

        int[] resultArray = new int[size];
        int index = 0;
        for (int value : uniqueValues) {
            resultArray[index++] = value;
        }

        return resultArray;
    }
    
}
