import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams  } from '@ionic/angular';
import { SearchService } from "../../services/search.service";
import { formatDate } from '@angular/common';
import { SenderPage } from 'src/app/pages/search/sender/sender.page';
import { OrganicEntityPage } from 'src/app/pages/search/organic-entity/organic-entity.page';
import  WordCloud from 'src/plugin/wordcloud2.js';
import { ViewEventPage } from 'src/app/pages/agenda/view-event/view-event.page';
import { PublicationDetailPage } from '../publications/view-publications/publication-detail/publication-detail.page';
import { DocumentDetailPage } from 'src/app/modals/document-detail/document-detail.page';
import { SearchCategory, SearchList } from 'src/app/models/search-document';
import { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-search',
  templateUrl: './search.page.html',
  styleUrls: ['./search.page.scss'],
})
export class SearchPage implements OnInit {

  // https params
  searchSubject: string;
  searchDocumentDate: string;
  searchSender: string;
  searchOrganicEntiry: string;
  searchDocTypeId: string;
  ordinance: string;

  searchCategories: SearchCategory[] = [];
  showSearchDocuments: SearchList[] = [];
  showCategory: string;
  searchDocuments: SearchList[] =[];

  showDocuments = false;
  showAdvanceSearch = false;

  showLoader: boolean;

  currentPath: string

  // See http://idangero.us/swiper/api/ for valid options.
  slideOpts = {
    slidesPerView: parseInt(`${window.innerWidth/147}`, 10),
    initialSlide: 0,
    speed: 400,
  }

  loadedAttachments:any;

  list = []

  windowWidth: number;

  type : "Agenda" | "Correspondencia" | "AccoesPresidenciais" | "ArquivoDespachoElect" | "AccoesPresidenciais & ArquivoDespachoElect" = "Agenda";
  select: boolean = false;

  showSearchInput = false

  constructor(private modalController: ModalController,
    private search: SearchService,
    private modalCtrl: ModalController,
    private navParams: NavParams,
    public ThemeService: ThemeService)
    {
      this.ordinance = "recent";
      this.currentPath= window.location.pathname;

      this.type = this.navParams.get('type');

      this.type = this.navParams.get('type');
      this.select = this.navParams.get('select');

      this.showSearchInput = this.navParams.get('showSearchInput');

      if(this.type == null || this.type == undefined) {

        if(this.currentPath  == '/home/agenda') {
          this.type = "Agenda"
        } else if (this.currentPath  =='/home/gabinete-digital') {
          this.type = "AccoesPresidenciais & ArquivoDespachoElect"

        } else if (this.currentPath  == '/home/publications') {
          this.type = "AccoesPresidenciais"
        } else {
          console.log('search bug!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        }
      }
  }

  selectItem(item: SearchList) {
    if(this.select){
      this.modalController.dismiss({
        selected: item
      });
    }

    return this.select;
  }

  ngOnInit() {

    this.wordCloud();

    window.onresize = (event) => {
      this.windowWidth = window.innerWidth
      this.loadWordCloud()
    };

    this.windowWidth = window.innerWidth

    window['dynamicSearch'] = (search:string) =>{
      this.searchSubject = search;
    }

    window['searchTriger'] = () =>{
      this.basicSearch();
    }

  }

  wordCloud() {

    this.search.mostSeachWord("15").subscribe(res=>{

      const container = document.querySelector('.seach-wrapper');

      // container.setAttribute('style',`width: ${window.innerWidth}px`);

      const highest= res[0].Hits;
      const lowest = res[res.length-1].Hits;
      const range =  highest - lowest;
      const perPercent = range / 100;
      let list = [];

      // minimum font sixe
      // Editable -----------------------------------
      const minimumSize = 9;
      // Editable ------------------------------------
      // 64
      const maximum = 64;

      res.forEach(e => {
        const array: any =  Object.values(e);

        array[1] = (((array[1] - lowest) / perPercent) * (maximum - minimumSize)/ 100 ) + minimumSize;
        list.push(array)
      });

      this.list = list

      console.log(this.list)

      const elem = document.documentElement.querySelector('.most-searched-word-container');

      setTimeout(()=>{
        WordCloud(
          elem,
          {
            list: this.list,
            Family: 'Times, serif',
            gridSize: 15
          },
        );
      },300)

    });
  }


  loadWordCloud() {

    setTimeout(()=>{
      const elem = document.documentElement.querySelector('.most-searched-word-container');

      WordCloud(
        elem,
        {
          list: this.list,
          Family: 'Times, serif',
          gridSize: 15
        },
      );

    }, 100);

  }

  close() {
    this.modalController.dismiss();
  }


  reorderList(orderBy: string) {

    this.ordinance = orderBy;

    if(this.ordinance == 'recent'){
      this.showSearchDocuments = this.sortArrayISODate(this.searchDocuments).reverse();
    } else {
      this.showSearchDocuments = this.sortArrayISODate(this.searchDocuments)
    }
  }

  sortArrayISODate(myArray: any) {
    return myArray.sort(function(a, b) {
      return (a.Data < b.Data) ? -1 : ((a.Data > b.Data) ? 1 : 0);
    });
  }

  /**
   * @description Basic search
   */
   basicSearch() {

    if(this.type == "Agenda" ){


      this.showLoader = true;

      this.search.basicSearch(this.searchSubject, this.searchDocumentDate, this.searchSender
        ,this.searchOrganicEntiry, this.searchDocTypeId, '0').subscribe(res=>{
        console.log(res);

        res.Categories.forEach( e => {
          e['Active'] = false;
        });

        // bind respose
        this.searchCategories = res.Categories;

        this.searchDocuments = this.sortArrayISODate(res.Documents);

        this.reorderList(this.ordinance);

        // hide show document
        if(this.searchDocuments.length >= 1){
          this.showDocuments = true;
        } else {
          this.showDocuments = false
        }

        this.showLoader = false;
        this.loadWordCloud();

      });
    }
    else if ( this.type == "AccoesPresidenciais & ArquivoDespachoElect"){

      this.showLoader = true;

      this.searchCategories = [];
      this.searchDocuments = [];
      this.showSearchDocuments = [];

      if(this.select) {

        let counter  = 0;

        this.search.searchForDoc(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '8').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });

          // bind respose

          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'Correspondencia'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }
          counter++;

          if(counter ==2){
            this.showLoader = false;
          }

          this.loadWordCloud();
        });

        this.search.searchForDoc(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '361').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });


          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'ArquivoDespachoElect'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }

          this.loadWordCloud();
          counter++;

          if(counter ==2){
            this.showLoader = false;
          }
        });

      } else {
        let counter = 0;

        this.search.basicSearch(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '8').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });

          // bind respose

          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'Correspondencia'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }

          counter++;

          if(counter ==2){
            this.showLoader = false;
          }

          this.loadWordCloud();
        });

        this.search.basicSearch(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '361').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });


          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'ArquivoDespachoElect'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }


          counter++;

          if(counter ==2){
            this.showLoader = false;
          }
          this.loadWordCloud();
        });
      }
    }


    else if ( this.type == "Correspondencia"){

      this.showLoader = true;

      this.searchCategories = [];
      this.searchDocuments = [];
      this.showSearchDocuments = [];

      if(this.select) {

        let counter  = 0;

        this.search.searchForDoc(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '8').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });

          // bind respose

          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'Correspondencia'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }
          counter++;

          if(counter ==2){
            this.showLoader = false;
          }
          this.showLoader = false;
          this.loadWordCloud();
        });

      } else {
        let counter = 0;

        this.search.basicSearch(this.searchSubject, this.searchDocumentDate, this.searchSender
          ,this.searchOrganicEntiry, this.searchDocTypeId, '8').subscribe(res=>{

          res.Categories.forEach( e => {
            e['Active'] = false;
            this.searchCategories.push(e)
          });

          // bind respose

          this.sortArrayISODate(res.Documents).forEach(e => {
            e['appName'] = 'Correspondencia'
            this.searchDocuments.push(e)
          });

          this.reorderList(this.ordinance);

          // hide show document
          if(this.searchDocuments.length >= 1){
            this.showDocuments = true;
          } else {
            this.showDocuments = false
          }

          counter++;

          if(counter ==2){
            this.showLoader = false;
          }

          this.loadWordCloud();
        });
      }
    }

    else if (this.type == "AccoesPresidenciais"){

      this.showLoader = true;

      this.search.basicSearch(this.searchSubject, this.searchDocumentDate, this.searchSender
        ,this.searchOrganicEntiry, this.searchDocTypeId, '386').subscribe(res=>{
        console.log(res);

        res.Categories.forEach( e => {
          e['Active'] = false;
        });

        // bind respose
        this.searchCategories = res.Categories;

        this.searchDocuments = this.sortArrayISODate(res.Documents);

        this.reorderList(this.ordinance);

        // hide show document
        if(this.searchDocuments.length >= 1){
          this.showDocuments = true;
        } else {
          this.showDocuments = false
        }

        this.showLoader = false;
        this.loadWordCloud();
      });
    }

   }

   /**
    * @description set empty value to searchSubject
    */
  clearSearchInput() {
    this.searchSubject = ""

    this.searchCategories = [];
    this.searchDocuments = [];
    this.showDocuments = false;

    this.wordCloud();
  }

  /**
   * @param isoDate String Iso date
   * @returns date in format  dd/MM/yyyy
   * @description convert Iso date to dd/MM/yyyy
   */
  formateIsoDate(isoDate:string): string{
    const date = new Date(isoDate);
    return formatDate(date, 'dd/MM/yyyy', 'pt');
  }

  activeCategoty(i){

    this.searchCategories.forEach((e, j) => {
      if(i != j){
        e['Active'] = false;
      }
    })

    if (this.searchCategories[i]['Active']){
      this.searchCategories[i]['Active'] = false;
    } else {
      this.searchCategories[i]['Active'] = true
    }
  }

  clearInputRemetente(){
    this.searchSender = "";
  }

  clearInputDocumentDate(){
    this.searchDocumentDate = "";
  }

  clearInputOrganicEntity(){
    this.searchOrganicEntiry = "";
  }

  /**
   * @description Clean inputs
   */
  showHideAdvanceSearch(show:boolean) {
    this.showAdvanceSearch = show;
  }

  async openAdvanceSearchSelection() {

    let classs;
    if( window.innerWidth <= 1024){
      classs = 'modal modal-desktop'
    } else  {
      classs = 'search-desktop-modal search-submodal'
    }

    const modal = await this.modalController.create({
      component: SenderPage,
      cssClass: classs,
      componentProps: {
      }
    });

    await modal.present();

    modal.onDidDismiss().then((data) => {
      this.searchSender = data.data;
    });

  }


  async openOrganicEntitySelection(){

    let classs;
    if( window.innerWidth <= 1024){
      classs = 'modal modal-desktop'
    } else  {
      classs = 'search-desktop-modal search-submodal'
    }

    const modal = await this.modalController.create({
      component: OrganicEntityPage,
      cssClass: classs,
      componentProps: {
      }
    });

    await modal.present();

    modal.onDidDismiss().then((data) => {
      this.searchOrganicEntiry = data.data;
    });

  }

  async filterDocList(categoryName:string){

    // show all category
    if(this. showCategory == categoryName ){

      this.showSearchDocuments = this.searchDocuments;

    } else { // filter category
      this.showSearchDocuments = this.searchDocuments.filter((e) => e.DocTypeDesc == categoryName);
    }

    this.showCategory = categoryName;
  }


  itemIcons(): string{
    return this.type
  }

  viewDocument(){
    const url: string = this.loadedAttachments.DocumentURL.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
    // const browser = this.iab.create(url,"_blank");
    // browser.show();
  }


  async viewDetail(searchDocument: SearchList) {

    const ApplicationType = searchDocument.ApplicationType.toString()
    const Id =  searchDocument.Id
    if(this.select == false){
      if(this.type == "Agenda") {

        const modal = await this.modalCtrl.create({
          component: ViewEventPage,
          componentProps:{
            eventId: Id,
            isModal: true,
            header: false
          },
          cssClass: 'modal modal-desktop',
        });
        await modal.present();
        modal.onDidDismiss().then((res)=>{});

      } else if(this.type == "AccoesPresidenciais"){

        this.viewPublicationDetail(Id);
      }
      else if(this.type == "AccoesPresidenciais & ArquivoDespachoElect"){

        if(ApplicationType == '8' || ApplicationType == '361') {
          this.viewDocumentDetail(Id, ApplicationType);
          // this.openExpedientActionsModal(searchDocument)
        }
      }
    }
  }

  async viewPublicationDetail(publicationId:string) {
    const modal = await this.modalController.create({
      component: PublicationDetailPage,
      componentProps:{
        publicationId: publicationId,
        isModal: true
      },
      cssClass: 'publication-detail modal modal-desktop ',
      //backdropDismiss: false
    });

    await modal.present();
    modal.onDidDismiss().then(()=>{});

  }

  async viewDocumentDetail(docId:string, applicationId:string) {
    let classs;

    if( window.innerWidth < 701) {
      classs = 'modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }

    const modal = await this.modalController.create({
      component: DocumentDetailPage,
      componentProps:{
        docId: docId,
        applicationId: applicationId,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{});


  }

}
