// 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, Inject, Output, EventEmitter} from '@angular/core';
import { Subscription } from 'rxjs';
import { Router } from '@angular/router';
import { ActivatedRoute, NavigationEnd } from "@angular/router";
import { IonicModule, ModalController } from '@ionic/angular';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
//import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { CartService } from 'src/app/providers/cart.service';
import { ConfigService } from 'src/app/providers/config.service';
import { SearchableSelectModule } from '../../components/searchable-select/searchable-select.module';

@Component({
  imports: [
   	CommonModule,
    FormsModule,
	  IonicModule,
    ReactiveFormsModule,
    TranslateModule,
    SearchableSelectModule,
  ],
  providers: [
    TranslateService,
  ],
  selector: 'app-modal-address',
  templateUrl: './modal-address.component.html',
  styleUrl: './modal-address.component.css',
  standalone: true,
})
export class ModalAddressComponent implements OnInit{

  constructor(
          private cartService: CartService,
          private translate: TranslateService,
          private configService: ConfigService,
          private router: Router,
          private activatedRoute: ActivatedRoute,
          private modalCtrl: ModalController,
          private formBuilder: FormBuilder
    ){}



  openModalComuni = false;

 ngOnInit(): void {
  }

  ionViewWillEnter() {

    this.Useraddress.uda_id = this.id;
    if(this.Useraddress.uda_id != 0){
      this.getById(this.Useraddress.uda_id);
    } else {
      this.prefillFromUser();
    }

  }

  prefillFromUser(){
    const user = this.configService.getUser();
    if (user) {
      this.Useraddress.firstname = user.usr_firstname || '';
      this.Useraddress.lastname = user.usr_lastname || '';
    }
  }



  id: number = 0;
  @Output() CloseModal = new EventEmitter<void>();
  cmp_id!:number;
  selectedComune: string[] = [];
  delivery_addressForm: any;
  selectedComuneText = '';
  paramsSubscription?: Subscription;
  comuni: any[] = [];
  objcomune: any = {denominazione: "", codiceprovincia:"", codicefiscale: "", cap:""};
  Useraddress : any = {uda_id: 0, cmp_id: 0, firstname: "", lastname:"", address:"", number:"", city:"", postal_code:"", city_code:"", prov:"", note:"", isactive: false};


  closeModal(): void {
    this.modalCtrl.dismiss();
		this.CloseModal.emit();
	}

  getById(uda_id: number){
     this.cartService.delivery_address_id(uda_id).subscribe(res => {
      this.Useraddress = res;
      this.getComune(this.Useraddress.city_code);
    });
  }

  upd(){
    this.cartService.delivery_address_upd(this.Useraddress).subscribe(() =>{
      this.closeModal();
    }
    );

  }

  insert(){
    this.cartService.delivery_address_add(this.Useraddress).subscribe(() =>{
      this.closeModal();
    }
    );

  }

  onSubmit() {
    this.Useraddress.cmp_id = this.cmp_id;
    this.Useraddress.firstname.trim();
    this.Useraddress.lastname.trim();
    if(this.objcomune.denominazione == ""){
      this.translate.get('onlineshop.notify.errcom').subscribe(res => {
        this.configService.presentToastError(res);
      });
    }
    else{
      this.Useraddress.city = this.objcomune.denominazione;
      this.Useraddress.postal_code = this.objcomune.cap;
      this.Useraddress.city_code = this.objcomune.codicefiscale;
      this.Useraddress.prov = this.objcomune.codiceprovincia;
      if (this.Useraddress.uda_id == 0) {
        this.insert();
        }
      else{
        this.upd();
        };
    }
  }


  sel_comune(event: any) {
    this.selectedComune = event;
    if (this.selectedComune.length > 0) {
      this.Useraddress.city_code = this.selectedComune[0]
      this.getComune(this.Useraddress.city_code);
    }
    this.openModalComuni = false;
  }

  getComune(filterValue: string){
    this.cartService.getComuniSelect(filterValue).subscribe((res: any) => {
			if (res) {
        this.comuni = res;
				this.objcomune = this.comuni.find(x => x.codicefiscale === this.Useraddress.city_code);
			}
		});
  }

}
