import {Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter, ChangeDetectorRef} from '@angular/core';
import {createQueryStringFromObject} from '../../../../../../shared/util/func';
import {FacultysService} from '../../../../../../core/service/settings/facultys.service';
import {tap} from 'rxjs/operators';
import {DepartmentService} from '../../../../../../core/service/settings/department.service';

@Component({
  selector: 'app-department-search',
  templateUrl: './department-search.component.html',
  styleUrls: ['./department-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DepartmentSearchComponent implements OnInit {
  faculty = [];
  filteredDepartmentList: any = [];
  @Output() add = new EventEmitter();
  @Output() search = new EventEmitter();
  query = {
    faculty_uid : null,
    department_uid : null
  };
  private curSub: any;
  constructor(
    private departMentSV: DepartmentService,
    private facultySV: FacultysService,
    private cdr: ChangeDetectorRef,
  ) { }

  ngOnInit(): void {
    this.facultySV.getAll().pipe(tap(x => {
      this.faculty = x;
    })).subscribe();
  }

  onAdd(){
    this.add.emit();
  }

  onSearch(){
    let query = createQueryStringFromObject(this.query);
    this.search.emit(query);
  }

  clear(){
    this.filteredDepartmentList = [];
    this.query = {
      faculty_uid : null,
      department_uid : null
    };
  }

  displayFacultyname(uid){
    if (uid && this.faculty) return this.faculty.find(x => x.faculty_uid === uid)?.faculty_name_th
    if (uid && !this.faculty) return this.curSub?.faculty_name_th
  }

  setDepartment(event){
    if (event != null){
      this.departMentSV.search(`?faculty_uid=${event}`).pipe(
        tap(x => this.filteredDepartmentList = x),
        tap(x => this.cdr.detectChanges())
      ).subscribe();
    }
  }

}
