import {Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter, ChangeDetectorRef} from '@angular/core';
import {createQueryStringFromObject} from '../../../../../../shared/util/func';
import {RegionService} from '../../../../../../core/service/region/region.service';
import {ProviceService} from '../../../../../../core/service/province/provice.service';

@Component({
    selector: 'app-testcenter-search',
    templateUrl: './testcenter-search.component.html',
    styleUrls: ['./testcenter-search.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestcenterSearchComponent implements OnInit {
    @Output() add = new EventEmitter();
    @Output() search = new EventEmitter();
    query = {
        branch_name_th : null,
        region_uid : null,
        province_uid : null,
    };
    regionMock = [];
    provinceMock = [];
    selectAlready = false;
    datanotReady = true;
    constructor(
        private regionSV: RegionService,
        private provinceSV: ProviceService,
        private cdr: ChangeDetectorRef,
    ) { }

    ngOnInit(): void {
        this.regionSV.getAll().subscribe(
            result => {
                this.regionMock = result;
                this.datanotReady = false;
            },
        );
        this.provinceSV.getAll().subscribe(
            result => {
                this.provinceMock = result;
                this.datanotReady = false;
            },
        );
    }

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

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

    clear(){
        this.query = {
            branch_name_th : null,
            region_uid : null,
            province_uid : null,
        };
    }

    setProvince(selectObject){
        if (this.selectAlready === true){
            this.provinceSV.getAll().subscribe(
                result => {
                    this.provinceMock = result;
                    this.provinceMock = this.provinceMock.filter((x) => {
                        return x.region_uid === selectObject;
                    });
                }
            );
        }else {
            this.provinceMock = this.provinceMock.filter((x) => {
                return x.region_uid === selectObject;
            });
            this.selectAlready = true;
        }
    }

}
