// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component, OnInit, ViewChild, } from '@angular/core';
import { Router } from '@angular/router';
import { InfiniteScrollCustomEvent, IonPopover } from '@ionic/angular';
import { ActivatedRoute } from "@angular/router";
import { Location } from '@angular/common';
import { Subscription, Subject, debounceTime, distinctUntilChanged } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';


import { ConfigService } from 'src/app/providers/config.service';
import { ProdService } from 'src/app/providers/prod.service';

@Component({
  selector: 'app-prod-filters',
  templateUrl: './prod-filters.component.html',
  styleUrl: './prod-filters.component.scss',
  standalone: false,
})

export class ProdFiltersComponent implements OnInit{

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private prodService: ProdService,
    private location: Location,
    private config: ConfigService,
    private translate: TranslateService,
    private configService: ConfigService,
  ) {}

 responsiveOptions: any[] = [
    { breakpoint: '1024px', numVisible: 5 },
    { breakpoint: '768px', numVisible: 3 },
    { breakpoint: '560px', numVisible: 1 }
  ];

  // VARIABILI

  imageBaseURL = "";
  onlineshopImageUrl = "";
  filterId?: number;
  filter: any = {};
  filter_temp: any = {};
  filtriModalOpen = false;
  ordinamentoModalOpen = false;
  lstOrdinamento: any[] = [];
  type: any;
  lstFilter: any[] = [];
  lstData: any[] = [];
  lst_typewine: any[] = [];
  lst_type_native_wine: any[] = [];
  lst_regioni: any[] = [];
  filterTypewine: any;
  totalrows = 0;
  selected_order:any;
  lstWines_bySearch: any[] = [];
  max_vote = 0;
  min!: number;
  max!: number;
  range: number[] = [];
  isOpenPopOverEdit = false;
  cur_data: any = {};
  isLogged = false;
  isSearching = false;
  cmp_id: number = 0;
  prt_id: number = 0;
  @ViewChild('popover_ordinamento_product', { static: false }) popover_ordinamento_product!: IonPopover;
  resetButtons = [
    {
      text: 'No',
      handler: () => {
      }
    },
    {
      text: 'Sì',
      cssClass: 'alert-button-confirm',
      handler: () => {
        this.resetFilter();
        this.search();
        this.filtriModalOpen = false;
      }
    }
  ];

  //-----------INIZIALIZZAZIONE PAGINA--------------------------------- 
  paramsSubscription?: Subscription;

  ngOnInit(): void {

    this.paramsSubscription = this.activatedRoute.params.subscribe((params) => {
			if (params['cmp_id']) this.cmp_id = +params['cmp_id'];
      if (params['prt_id']) this.prt_id = +params['prt_id'];
		});

    this.imageBaseURL = this.config.imageBaseURL;
    this.onlineshopImageUrl = this.config.onlineshopImageUrl;
    fetch('./assets/config/sort_product.json').then(res => res.json()).then(json => {
      this.lstOrdinamento = json;
    });

    this.resetFilterTypeWine();

    this.prodService.get_typewine(this.filterTypewine).subscribe(res => {
      this.lst_typewine = res;
    });
    
    this.ViewWillEnter();

    this.paramsSubscription = this.activatedRoute.params.subscribe(params => {
      if (+params["id"]) {
        this.filter.type_wine = +params["id"];
      } else {
        this.filter.type_wine = -1;
      }
    });

    this.search();
  }
  

  ViewWillEnter() {
    this.lstData = [];
    this.resetFilter();
  }

  ngOnDestroy() {
		this.paramsSubscription?.unsubscribe();
	}

  // RESET FILTERS
  resetFilter() {
    this.range = [];
    this.filter = {};
    this.filter.cmp_id = this.cmp_id;
    this.filter.pagina = 1;
    this.filter.righePagina =20;
    this.filter.orderBy = 'prd_title';
    this.filter.type_wine = -1;
    this.filter.price_from = null;
    this.filter.price_to = null;
    this.filter.fav = false;
    this.lstFilter = [];
    this.MinMaxProd();
  }
    
  resetFilterTypeWine(){
    this.filterTypewine = {};
    this.filterTypewine.tpw_cmp_id = this.cmp_id;
    this.filterTypewine.pagina = 1;
    this.filterTypewine.righePagina = 99999;
    this.filterTypewine.orderBy = 'tpw_name';
  }

  reset(){
    this.resetFilter();
    this.lstData = [];
    this.search();
  }


  // ----------------ORDINAMENTO E FILTRI----------------------

  // PREZZO E TIPOLOGIA
  inputMax!: number;
  inputMin!: number;
  MinMaxProd(){
      this.prodService.MinMaxPrd(this.filter).subscribe(res => {
      this.min = res.min;
      this.max = res.max;
      this.inputMax = res.max;
      this.inputMin = res.min;
      this.range[this.min, this.max];
    });
  }
  set_min_max() {
  this.range = [this.inputMin,this.inputMax]; 
  }
  set_range(){
  this.inputMin = this.range[0];
  this.inputMax = this.range[1];
  }
  openFiltri() {
    this.filtriModalOpen = true;

    this.filter_temp = {};
    this.filter_temp.type_wine = this.filter.type_wine;
    this.filter_temp.price_from = this.filter.price_from;
    this.filter_temp.price_to = this.filter.price_to;
  }
  searchFilter() {
    this.filter.pagina = 1;
    this.filter.righePagina = 20;
    this.filter.type_wine = this.filter_temp.type_wine;
    this.filter.price_from = this.range[0];
    this.filter.price_to = this.range[1];
    this.lstFilter = [];
    this.filtriModalOpen = false;
    this.lstData = [];
    this.search();
  }

  // ORDINAMENTO
  viewOrdinamentoModal(e: Event) {
    this.popover_ordinamento_product.event = e;
    this.ordinamentoModalOpen = true;
  }
  setOrdinamento(ord: any) {
    this.filter.orderBy = ord;
    this.ordinamentoModalOpen = false;
    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }

  // RICERCA
  getPrdbySearch(string_search: String) {
    let new_string = string_search.trim();
    this.filter.description = new_string;
    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }

  // PREFERITI
  notFav(){
    this.filter.fav = false;
    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }
  fav(){
    this.filter.fav = true;
    this.lstData = [];
    this.filter.pagina = 1;
    this.search();
  }

  // ------------SERACH LISTA PRODOTTI------------------------------
  search(setTotal = true) {
    this.isSearching = true;
    this.prodService.lstProducts(this.filter).subscribe(res => {
      if (setTotal) {
        this.totalrows = 0;
        if (res[0]) {
          this.totalrows = res[0].totalrows;
        }
      }

      res.forEach((element: any) => {
        this.lstData.push(element);
      });
      this.isSearching = false;
    });
  }

  // INDIRIZZAMENTI E INFINITE SCROLL

  prd_detail(prd_id: number){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'product-detail', prd_id ]);
  }

  goBack(): void {
    this.location.back();
  }

  onIonInfinite(ev: any) {
    this.filter.pagina++;
    this.search(false);

    if (ev) {
      setTimeout(() => {
        (ev as InfiniteScrollCustomEvent).target.complete();
      }, 1000);
    }
  }

}
