import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild, HostListener } from '@angular/core';
import { SelectableSettings } from '@progress/kendo-angular-grid';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { Subscription } from 'rxjs';
import { CustomerAddress } from 'src/app/models/customer-address.model';
import { AddressCustomerService } from 'src/app/services/address-customer.service';

@Component({
  selector: 'app-select-address',
  templateUrl: './select-address.component.html',
  styleUrls: ['./select-address.component.scss']
})
export class SelectAddressComponent implements OnInit, OnDestroy {
  constructor(private addressService: AddressCustomerService) { }
  
  isSmallScreen: boolean;
  address: CustomerAddress[] = [];
  addressSubscription: Subscription;
  public selectableSettigns: SelectableSettings = {
    checkboxOnly: false
  };
  @ViewChild('searchText') searchText: TextBoxComponent;
  @Input() openedDialog = false;
  @Input() customerId: number;
  @Output() resultEvent = new EventEmitter<CustomerAddress>();
  customerAddresses: CustomerAddress[] = [];
  customerAddress: CustomerAddress;

  ngOnInit(): void {
    this.isSmallScreen = window.innerWidth < 768;
    this.addressSubscription = this.addressService.getAddress(this.customerId)
        .subscribe((res: CustomerAddress[]) => {
          this.customerAddresses = res;
          this.customerAddress = this.customerAddresses[0];
          console.log(this.customerAddresses);
        });
  }

  ngOnDestroy(): void {
    if (this.addressSubscription) {
      this.addressSubscription.unsubscribe();
    }
  }

  selectionCustomer(event) {
    const selCustomer = event.selectedRows[0].dataItem as CustomerAddress;
    this.customerAddress = selCustomer;
    this.openedDialog = false;
    this.resultEvent.emit(this.customerAddress);
  }

  close() {
    this.openedDialog = false;
    this.resultEvent.emit(null);
  }

  @HostListener('window:resize', ['$event'])
  onResize(event: any): void {
    this.isSmallScreen = event.target.innerWidth < 768; // Atualiza em tempo real
  }
}
