import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ModalDismissReasons, NgbModal, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
import { debounceTime, distinctUntilChanged, filter, map, merge, Observable, OperatorFunction } from 'rxjs';
import { Subject } from 'rxjs/internal/Subject';
import { Contact } from 'src/app/models/contact.model';
import { ContactService } from 'src/app/service/contact.service';

const pages = ['หน้าหลัก', 'รายการอุปกรณ์', 'รายการจอง-เบิกทั้งหมด'];

@Component({
  selector: 'app-contact-admin',
  templateUrl: './contact-admin.component.html',
  styleUrls: ['./contact-admin.component.scss']
})
export class ContactAdminComponent implements OnInit {
  model: any;

  closeResult = '';

  page = 1;
  pageSize = 10;
  collectionSize = 0;

  pageListRoom = 1;
  pageSizeListRoom = 10;
  collectionSizeListRoom = 0;

  listContact: Contact[] = [];

  modelContact = new Contact();

  myFormContact: FormGroup;
  myFormAddContact: FormGroup;

  sDate = "";



  @ViewChild('instance', { static: true }) instance: NgbTypeahead;
  focus$ = new Subject<string>();
  click$ = new Subject<string>();

  constructor(private ContactService: ContactService, private modalService: NgbModal) { }

  ngOnInit(): void {
    this.ContactService.getListContact().subscribe( result => {
      this.listContact = result;
    });
    this.collectionSizeListRoom = this.listContact.length;
    this.collectionSize = this.listContact.length

    this.myFormAddContact = new FormGroup({
      ctName: new FormControl('', [Validators.required]),
      ctDesc: new FormControl(''),
      ctTab: new FormControl('', [Validators.required]),
      ctHead: new FormControl('', [Validators.required]),
      sDate: new FormControl('', [Validators.required]),
      ctStatus: new FormControl('')
    });
  }

  search: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
      map(term => (term === '' ? pages
        : pages.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))
    );
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  openContact(content: string, item: Contact) {
    this.modelContact = item;

    let sDate = this.modelContact.sDate.split('/')
    this.sDate = sDate[0] + "-" + sDate[1] + "-" + sDate[2]

    this.myFormContact = new FormGroup({
      ctName: new FormControl(this.modelContact.ctName, [Validators.required]),
      ctDesc: new FormControl(this.modelContact.ctDesc),
      ctTab: new FormControl(this.modelContact.ctTab, [Validators.required]),
      ctHead: new FormControl(this.modelContact.ctHead, [Validators.required]),
      sDate: new FormControl(this.modelContact.sDate, [Validators.required]),
      ctStatus: new FormControl(this.modelContact.ctStatus)
    });

    this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
    console.log("date", this.modelContact)
  }

  saveContact() {
    this.modelContact.sDate = this.modelContact.sDate.split("-")[0] + "/" + this.modelContact.sDate.split("-")[1] + "/" + this.modelContact.sDate.split("-")[2];
    this.modelContact.ctStatus = 0;

    this.ContactService.addContact(this.modelContact);
    this.modalService.dismissAll();
    this.ngOnInit();
  }

  saveStatusContact() {

    this.modelContact.ctName = this.myFormContact.value.ctName
    this.modelContact.ctDesc = this.myFormContact.value.ctDesc
    this.modelContact.ctTab = this.myFormContact.value.ctTab
    this.modelContact.ctHead = this.myFormContact.value.ctHead
    this.modelContact.ctStatus = this.myFormContact.value.ctStatus
    this.modelContact.sDate = this.myFormContact.value.sDate
    this.ContactService.updateContact(this.modelContact)
    this.modalService.dismissAll();
    this.ngOnInit();
  }

  openAdd(addContact) {
    this.modelContact = new Contact;

    this.myFormContact = new FormGroup({
      ctName: new FormControl(this.modelContact.ctName, [Validators.required]),
      ctDesc: new FormControl(this.modelContact.ctDesc),
      ctTab: new FormControl(this.modelContact.ctTab, [Validators.required]),
      ctHead: new FormControl(this.modelContact.ctHead, [Validators.required]),
      sDate: new FormControl(this.modelContact.sDate, [Validators.required]),
      ctStatus: new FormControl(this.modelContact.ctStatus)
    });

    this.modalService.open(addContact, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }
}

