/*
  But :    contrôleur de la page d'index
  Auteur : Luca Dias Madeira
  Date :   20.06.2021 / V1.9
*/


//actions faites au chargement de la page
$().ready(function () {
    //créé une instance de la classe ctrl
    ctrl = new Ctrl();

    //donne les valeurs aux attribut du Worker lié à ce ctrl
    ctrl.research.listeCategories = ctrl.research.obtainCategory();
    ctrl.research.listeFirstLetter = ctrl.research.obtainFirstLetter();
    ctrl.research.listeGlasses = ctrl.research.obtainGlass();
    ctrl.research.cocktailfilters = ctrl.research.obtainCocktailFilters();
    ctrl.research.ingredientfilters = ctrl.research.obtainIngredientFilters();

    //affiche les filtres pour pouvoir commencer les recherches
    ctrl.showAvailableFilters();
});
  
  class Ctrl {
      //constructor de la classe
      constructor() {
        this.research = new Research();
      }
  
      //donne les filtres valides de l'objet recherché (cocktail ou ingrédient)
      showAvailableFilters() {
          let changeFilter = this.research.showfilters(document.getElementById("whatToSearch"));
          
          changeFilter(this);

          $("#indicationInput").html('<input type="text" size="20" id="whatForIndication" name="whatForIndication" placeholder="indication...">');
          
          $("#rechercherbtn").html('<a href="#search" onclick="ctrl.recherche();">SEARCH</a>');
      }
      
      //adapte le champ d'indication selon la classe du filtre
      adaptIndicationInput() {
        $("#indicationInput").html('<input type="text" size="20" id="whatForIndication" name="whatForIndication" placeholder="indication...">');

        let choosenClassReference = $('#filterSelection select option:selected').attr('class');
        let isFilter = $('#filterSelection select option:selected').attr('value').includes("filter.php");
        
        let commands = this.research.adaptindication(choosenClassReference, isFilter);
        let commande1 = commands[0];
        let commande2 = commands[1];
        commande1(this);
        commande2();
      }

      //lance la méthode corresponante à la recherche faite
      recherche() {

        let urlResearchTypeValue = $('#filterSelection select option:selected').attr('value');
        let classechoisieParam = $('#filterSelection select option:selected').attr('class');
        let urlParamSelectorIndicators = $('#indicationInput #whatAsFilter option:selected').val();
        let urlParamDefaultValue = $("#whatForIndication").val();
        let whatToSearch = $("#cocktailOrIngredient select option:selected").attr("value");

        let searchInfo = this.research.rechercher(this, urlResearchTypeValue, classechoisieParam, urlParamSelectorIndicators, urlParamDefaultValue, whatToSearch);
        $(".pg2").html("");
        $(".pg3").html("");

        //choix de quel commande faire
        switch (searchInfo.type) {
            case "multipleCocktails":
                this.rechercherPlusieursCocktails(searchInfo.url);
                break;

            case "singleCocktail":
                this.rechercherUnCocktail(searchInfo.url);
                break;

            default:
                this.rechercherUnIngredient(searchInfo.url);
                break;
        }
      }

      //lance la recherche pour plusieurs cocktails
      rechercherPlusieursCocktails(url) {
        ///voir si c'est une recherche en filtre
        let obtentionEnFiltre = $('#filterSelection select option:selected').attr('value').includes("filter.php");

        this.research.obtainMultipleCocktailResults(url, this.afficherPlusieursCocktails, obtentionEnFiltre);
      }

      //lance la recherche pour un seul cocktail
      rechercherUnCocktail(url) {
          this.research.obtainSingleCocktailResult(url, this.afficherUniqueCocktail, this.afficherPetitsIngredients);
      }

      //lance la recherche pour un seul ingrédient
      rechercherUnIngredient(url) {
          this.research.obtainSingleIngredientResult(url, this.afficherUniqueIngredient, this.afficherPetitsCocktails);
      }

      //affiche plusieurs cocktails
      afficherPlusieursCocktails(data, obtentionEnFiltre) {
        $('.pg2').html("");
        $('.pg3').html("");

        let a = data.drinks;
        if (a === null || a === undefined) {

        } else {
            if (obtentionEnFiltre) {
                let contenu = '<h2>'+'Cocktails corresponding to criteria :'+'</h2>';
                let singleElement;
                let longueur = a.length;
                for (let i = 0; i < longueur; i++) {
                  let drink = a[i];
                  singleElement = '<div><ul>';
                  singleElement += '<li>'+'<img alt='+'"'+drink.idDrink+'"'+' class="preview" src='+'"' + drink.strDrinkThumb +'/preview"'+ '>' + '</li>'; //image
                  let tempvar = "'"+drink.idDrink+"'";
                  singleElement += '<li><a href="#'+drink.strDrink+'" onclick="ctrl.showElement(0, '+tempvar+');"><p>'+drink.strDrink+'</p></a></li>'
                  singleElement += '</ul></div>';
                  contenu += singleElement;
                }
                $('.pg2').html(contenu);
            } else {
                  let longueur = a.length;
                  let contenu = "";
                  let oneElement;
                  let tags = "";
                  let tagList;
                  let Ingredients = "";
                  for (let i = 0; i < longueur; i++) {
                      let drink = a[i];
                      if (drink.strTags !== undefined) {
                      } else {
                          drink = obtainCocktailInformations(drink.idDrink);
                      }
      
                      oneElement = '<div><ul>'; //début entrée
      
      
                      //POSSIBLE AMELIORATION
                      oneElement += '<li>'+'<img alt='+'"'+drink.idDrink+'"'+' class="preview" src='+'"' + drink.strDrinkThumb +'/preview"'+ '>' + '</li>'; //image
                      //
      
      
                      
                      oneElement += '<li>'; //début liste
                      oneElement += '<a href="#'+drink.strDrink+'" onclick="ctrl.showElement(0, '+drink.idDrink+');"><p>'+drink.strDrink+'</p></a>'; //nom cocktail
      
      
      
                      //POSSIBLE AMELIORATION
                      let tempvar = "'"+drink.strCategory+"'";
                      oneElement += '<p><a href="#'+drink.strCategory+'" onclick="ctrl.showElement(2, '+tempvar+');"'+'>'+drink.strCategory+'</a> | ';
                      let tempvar2 = "'"+drink.strGlass+"'";
                      oneElement += '<a href="#'+drink.strGlass+'" onclick="ctrl.showElement(3, '+tempvar2+');"'+'>'+drink.strGlass+'</a> | <br/>'+drink.strAlcoholic+'</p>'; //catégorie, alcool et verre
                      //
      
      
                      //tags
                      tags = "No Tags";
                      if (drink.strTags !== null) {
                          tags = "Tags : ";
                          if (drink.strTags.includes(',')) {
                              tagList = drink.strTags.split(',');
                              tagList.forEach(tag => {
                                  tags += tag + ', ';
                              });
                          } else {
                              tags += drink.strTags;
                          }
                      }
      
                      oneElement += '<p>'+tags+'</p>'; //nom cocktail
                      oneElement += '<p class="instructions">'+drink.strInstructions+'</p>'; //instructions
      
      
                      //quantités + ingrédients
                      Ingredients = "If you see this message, someone forgot to say what ingredients are used";
                      if (drink.strIngredient1 !== null) {
                          Ingredients = "";
                          let strName = "";
                          let strQName = "";
                          let strNameAfter = "";
                          let y = 0;
                          let finalresult = "";
                          for (let i = 1; i <= 15; i++) {
                              y = i+1;
                              strName = "strIngredient"+i;
                              strNameAfter = "strIngredient"+y;
                              strQName = "strMeasure"+i;
                              if (drink[strName] !== null) {
                                  if (drink[strQName] != null) {
                                      finalresult = drink[strQName]+' '+drink[strName];
                                  } else {
                                      finalresult = drink[strName];
                                  }
                                  
                                  //A REVERIFIER
                                  let tempvar = "'"+drink[strName]+"'";
                                  Ingredients += '<a href="#'+drink[strName]+'" '+'onclick="ctrl.showElement(1, '+tempvar+');"'+' >'+finalresult+'</a>';
                                  //
                              }  
                          }
                      }
                      oneElement += '<p>'+Ingredients+'</p>';
                      oneElement += '</li>' //fin liste
                      oneElement += "</ul></div>"; //fin entrée
      
      
                      contenu += oneElement;
                  }
                  $(".pg2").html(contenu);
      
                  //supprimer les noms mis dans la seconde section vu que inutile sauf pour le oneElement result
                  $("#rechercherbtn a").html('SEARCH (done)');
                  if (longueur > 1) {
                      $('.pg3').html("");
                  }
              }
            
            
        }
      }

      //affiche un unique cocktail
      afficherUniqueCocktail(data, afficherPetitsIngredients) {
          let a = data.drinks;
          if (a === null || a === undefined) {

          } else {
                let contenu = "";
                let oneElement;
                let tags = "";
                let tagList;
                let Ingredients = "";

                    let drink = a[0];
                    if (drink.strTags !== undefined) {
                    } else {
                        drink = obtainCocktailInformations(drink.idDrink);
                    }

                    oneElement = '<div><ul>'; //début entrée


                    //POSSIBLE AMELIORATION
                    oneElement += '<li>'+'<img alt='+'"'+drink.idDrink+'"'+' class="preview" src='+'"' + drink.strDrinkThumb +'/preview"'+ '>' + '</li>'; //image
                    //


                    
                    oneElement += '<li>'; //début liste
                    oneElement += '<p>'+drink.strDrink+'</p>'; //nom cocktail



                    //POSSIBLE AMELIORATION
                    let tempvar = "'"+drink.strCategory+"'";
                    oneElement += '<p><a href="#'+drink.strCategory+'" onclick="ctrl.showElement(2, '+tempvar+');"'+'>'+drink.strCategory+'</a> | ';
                    let tempvar2 = "'"+drink.strGlass+"'";
                    oneElement += '<a href="#'+drink.strGlass+'" onclick="ctrl.showElement(3, '+tempvar2+');"'+'>'+drink.strGlass+'</a> | <br/>'+drink.strAlcoholic+'</p>'; //catégorie, alcool et verre
                    //


                    //tags
                    tags = "No Tags";
                    if (drink.strTags !== null) {
                        tags = "Tags : ";
                        if (drink.strTags.includes(',')) {
                            tagList = drink.strTags.split(',');
                            tagList.forEach(tag => {
                                tags += tag + ', ';
                            });
                        } else {
                            tags += drink.strTags;
                        }
                    }

                    oneElement += '<p>'+tags+'</p>'; //nom cocktail
                    oneElement += '<p class="instructions">'+drink.strInstructions+'</p>'; //instructions


                    //quantités + ingrédients
                    Ingredients = "If you see this message, someone forgot to say what ingredients are used";
                    if (drink.strIngredient1 !== null) {
                        Ingredients = "";
                        let strName = "";
                        let strQName = "";
                        let strNameAfter = "";
                        let y = 0;
                        let finalresult = "";
                        let ingredientNames = ""; //pour le single cocktail result
                        for (let i = 1; i <= 15; i++) {
                            y = i+1;
                            strName = "strIngredient"+i;
                            strNameAfter = "strIngredient"+y;
                            strQName = "strMeasure"+i;
                            if (drink[strName] !== null) {
                                if (drink[strQName] != null) {
                                    finalresult = drink[strQName]+' '+drink[strName];
                                } else {
                                    finalresult = drink[strName];
                                }
                                
                                //A REVERIFIER
                                let tempvar = "'"+drink[strName]+"'";
                                Ingredients += '<a href="#'+drink[strName]+'" '+'onclick="ctrl.showElement(1, '+tempvar+');"'+' >'+finalresult+'</a>';
                                //
                                ingredientNames += drink[strName]+','+drink[strQName];
                                
                                if (drink[strNameAfter] !== null) {
                                    Ingredients += ' | ';
                                    ingredientNames += ' | ';
                                }
                                
                            }  
                        }
                        $('.pg3').html(ingredientNames);
                    }
                    oneElement += '<p>'+Ingredients+'</p>';
                    oneElement += '</li>' //fin liste
                    oneElement += "</ul></div>"; //fin entrée
    

                    contenu += oneElement;
                
                $(".pg2").html(contenu);

                //supprimer les noms mis dans la seconde section vu que inutile sauf pour le oneElement result
                $("#rechercherbtn a").html('SEARCH (done)');
                
          }
          afficherPetitsIngredients();
      }

      //affiche un unique ingrédient
      afficherUniqueIngredient(data, afficherPetitsCocktails, obtainSmallCocktailsResults) {
          //ici code pour afficher le grand ingredient dans la zone pg2 + description
          let a = data.ingredients;
            if (a === null || a === undefined) {

            } else {
                let contenu = "";
                let oneElement;
                let putAsAlcohol = "";
                let ingred = a[0];

                oneElement = "<div><ul>"; //début entrée
                oneElement += '<li>'+'<img alt='+'"'+ingred.idIngredient+'"'+' class="ingredient" src='+'"'+'https://www.thecocktaildb.com/images/ingredients/'+ ingred.strIngredient +'-Medium.png"'+ '>' + '</li>'; //image
                oneElement += '<li>'; //début liste
                oneElement += '<p>'+ingred.strIngredient+'</p>'; //nom ingredient
                
                
                putAsAlcohol = ingred.strType;
                if (ingred.strAlcohol != null) {
                    putAsAlcohol += ' | '+'Contains Alcohol';
                    if (ingred.strABV != null) {
                        putAsAlcohol += ' ('+ingred.strABV+'%)';
                    }
                }
                if (putAsAlcohol != null) {
                    oneElement += '<p>'+putAsAlcohol+'</p>'; //catégorie, alcool et taux d'alcool
                }
                oneElement += "</li></lu></div>";
                contenu = oneElement;

                if (ingred.strDescription != null) {
                    contenu += '<p class="ingredDesc">'+ingred.strDescription+'</p>';
                }


                $(".pg3").html("");
                let urlForSmallCocktail = 'https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=' + ingred.strIngredient;
                obtainSmallCocktailsResults(urlForSmallCocktail, afficherPetitsCocktails);
                $(".pg2").html(contenu);
                $("#rechercherbtn a").html('SEARCH (done)');
            }
      }

      //affiche plusieurs ingrédients d'un cocktail
      afficherPetitsIngredients() {
        let contenu = '<h2>'+'Ingredients used :'+'</h2>';
        let oneElement = "";

        if ($('.pg3').html().includes(' | ')) {
            let ingredients = $('.pg3').html().split(' | ');
            let QandI = "";
            let textToPut = "";
            let isOk = false;
            //contenu = '<article>';
            ingredients.forEach(ingredient => {
                if (!(ingredient == ',')) {
                    QandI = ingredient.split(',');
                    if (QandI[0] == null || QandI[0] === undefined) {
                        isOk = false;
                    } else if(QandI[1] != null) {
                        textToPut = QandI[0];
                        isOk = true;
                    } else {
                    textToPut = QandI[1]+' '+QandI[0];
                        isOk = true;
                    }
                    if (isOk) {
                        let tempvar = "'"+QandI[0]+"'";
                        oneElement = '<div><ul><li class="img"><img  '+'onclick="ctrl.showElement(true, '+QandI[0]+')"'+' class="ingredient" src="https://www.thecocktaildb.com/images/ingredients/'+QandI[0]+'-Medium.png"></li>';
                        oneElement += '<li><p>'+'<a href="#'+QandI[0]+'" '+'onclick="ctrl.showElement(1, '+tempvar+');"'+' >'+textToPut+'</a>'+'</p></li></ul></div>';
                        contenu += oneElement;
                    }
                }
                
                
            });
            $('.pg3').html(contenu);
            let instructionsFormated = $('.instructions').html().replaceAll(". ",".<br/>");
            console.log()
            let iFC = '<article><h1>Instructions :</h1><h3>'+instructionsFormated+'</h3></article>';
            $('.pg2').html($('.pg2').html()+iFC);
            $('.instructions').remove();
        } else {

            //EN PLUS JOLI
            $('.pg3').html("");
            //  

        } 
      }

      //affiche plusieurs cocktail ayant un ingrédient
      afficherPetitsCocktails(data) {
          let contenu = '<h2>'+'Cocktails using that ingredient :'+'</h2>';
          let singleElement;
          let a = data.drinks;
          let longueur = a.length;
          for (let i = 0; i < longueur; i++) {
            let drink = a[i];
            singleElement = '<div><ul>';
            singleElement += '<li>'+'<img alt='+'"'+drink.idDrink+'"'+' class="preview" src='+'"' + drink.strDrinkThumb +'/preview"'+ '>' + '</li>'; //image
            let tempvar = "'"+drink.idDrink+"'";
            singleElement += '<li><a href="#'+drink.strDrink+'" onclick="ctrl.showElement(0, '+tempvar+');"><p>'+drink.strDrink+'</p></a></li>'
            singleElement += '</ul></div>';
            contenu += singleElement;
          }
          $('.pg3').html(contenu);
      }

      //renvois à la fonction permettant de faire une recherche depuis un lien
      showElement(whatIsIt, elementReference) {
        this.research.showDetails(whatIsIt, elementReference, this);
      }
      
  }
  
  
