import { TelepulesService } from '../shared/telepules.service';
import { Telepules } from '../shared/telepules';
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormControl } from '@angular/forms';

import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
    @Output() selectedIranyitoSzamChanged = new EventEmitter<google.maps.LatLng>();

    telepulesek: Map<string, Telepules>;
    placeholder = '';
    iranyitoszamInput: FormControl;

    constructor(private telepulesekService: TelepulesService) {
        this.iranyitoszamInput = new FormControl();
    }

    ngOnInit() {
        this.telepulesek = this.telepulesekService.getTelepulesekIranyitoSzamMap();
        this.handleIranyitoszamInput();
    }

    private handleIranyitoszamInput(): void {
        this.iranyitoszamInput.valueChanges
            .pipe(
                map(data => {
                    data = data.replace(/(\D)/, '');
                    return data;
                }),
                debounceTime(300),
                distinctUntilChanged()
            )
            .subscribe(data => {
                if (data.length === 4) {
                    const telepules = this.telepulesek.get(data);
                    if (telepules) {
                        this.selectedIranyitoSzamChanged.emit(new google.maps.LatLng(telepules.lat, telepules.lng));
                        this.placeholder = this.createPlaceHolderText(telepules);
                        this.iranyitoszamInput.setValue('');
                    }
                } else {
                    this.iranyitoszamInput.setValue(data);
                }
            });
    }

    private createPlaceHolderText(telepules: Telepules): string {
        let telepulesresz = '';
        if (telepules.telepulesResz) telepulesresz = ', ' + telepules.telepulesResz;
        return telepules.iranyitoSzam + ' (' + telepules.nev + telepulesresz + ')';
    }
}
