// 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, Input, Output, EventEmitter, ApplicationRef } from '@angular/core';
import { Observable,} from 'rxjs'; // necessario per leggere e contenere 
import { InfiniteScrollCustomEvent } from '@ionic/angular';
import { Item } from '../../models/item';
import { CartService } from 'src/app/providers/cart.service';
/* import { LoadingService } from 'src/app/providers/loading.service'; */

@Component({
	selector: 'app-searchable-select',
	templateUrl: './searchable-select.component.html',
	styleUrls: ['./searchable-select.component.scss'],
	standalone: false,
})
export class SearchableSelectComponent implements OnInit {
	@Input() items: Item[] = [];
	@Input() comuni: any[] = [];
	@Input() selectedItems: string[] = [];
	@Input() title = 'Select Items';
	@Input() multiple? = false;

	@Output() selectionCancel = new EventEmitter<void>();
	@Output() selectionChange = new EventEmitter<string[]>();

	filteredItems: Item[] = [];
	workingSelectedValues: string[] = [];
	filteredItemsView: Item[] = [];

	constructor(private appRef: ApplicationRef, private cartService: CartService,/* , private loadingService: LoadingService */) {}

	/* ionViewWillEnter(){
    this.loadingService.show();
  }

  ionViewDidEnter(){
    this.loadingService.hide();
  } */

	ngOnInit() {
		this.filteredItems = [...this.items];
		this.workingSelectedValues = [...this.selectedItems];
		this.onIonInfinite(null);
	}

	trackItems(index: number, item: Item) {
		return item.value;
	}

	cancelChanges() {
		this.selectionCancel.emit();
	}

	confirmChanges() {
		this.selectionChange.emit(this.workingSelectedValues);
	}

	handleInput(ev: any) {
		this.filteredItems=[];

		const filterValue = ev.detail.value || '';
		if (filterValue.length >= 3 || filterValue === '') {
			this.cartService.getComuniSelect(filterValue).subscribe((res: any) => {
				if(res){
				res.forEach((element: any) => {
          		let d: any = { text: element.denominazione, value: element.codicefiscale};
          		this.filteredItems.push(d);
        		});

				const query = ev.target.value.toLowerCase();
				if (query) {
					this.filteredItemsView = this.filteredItems.filter((item) => {
						return item.text.toLowerCase().includes(query);
					});
				} else {
					this.onIonInfinite(null);
				}

				this.filteredItemsView.sort((a, b) => a.text.localeCompare(b.text));
				this.appRef.tick();
				}	
			});
		}
		
	}


	isChecked(value: string) {
		return this.workingSelectedValues.find((item) => item === value);
	}

	checkboxChange(ev: any) {
		const { checked, value } = ev.detail;

		if (checked) {
			if (!this.multiple) {
				this.workingSelectedValues = [];
				this.workingSelectedValues.push(value);
				this.selectionChange.emit(this.workingSelectedValues);
			} else {
				this.workingSelectedValues = [...this.workingSelectedValues, value];
			}
		} else {
			this.workingSelectedValues = this.workingSelectedValues.filter((item) => item !== value);
		}
	}

	onIonInfinite(ev: any) {
		let index = 0;
		for (let i = this.filteredItemsView.length; i < this.filteredItems.length; i++) {
			if (index > 20) {
				break;
			}

			this.filteredItemsView.push(this.filteredItems[i]);
			index++;
		}

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