import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { OnlineBoardFlightNumberFilterValidationService } from '@online-board/components/filter/components/flight-number-filter/services/online-board-flight-number-filter-validation.service';
import { IOnlineBoardRouteData } from '@online-board/types';
import { OnlineBoardFiltersStateService } from '@shared/services/filters/online-board-filters-state.service';
import { UserLocationService } from '@shared/services/user-location/user-location.service';
import { IParsedFlightId } from '@typings/flight/flight-id';
import { OnlineBoardApiService } from '@online-board/services/api.service';
import { StateService } from '@shared/services/state.service';

@Component({
    selector: 'online-board-flight-number-filter',
    templateUrl: './flight-number-filter.component.html',
    providers: [OnlineBoardFlightNumberFilterValidationService],
})
export class OnlineBoardFlightNumberFilterComponent {
    @Input() minDate: Date;
    @Input() maxDate: Date;
    disabledDates: Date[];

    @Output() onSearch = new EventEmitter<IParsedFlightId>();

    constructor(
        public validationService: OnlineBoardFlightNumberFilterValidationService,
        private apiService: OnlineBoardApiService,
        private route: ActivatedRoute,
        private locationService: UserLocationService,
        private state: OnlineBoardFiltersStateService,
        private stateService: StateService,
    ) {
    }

    ngOnInit() {
        this.route.data.subscribe((data: IOnlineBoardRouteData) => {
            // There is no urlParams.flightNumber field
            // in data object if flight number search page
            // isn't opened
            if (!data.urlParams?.flightNumber) {
                return;
            }
            this.setState(data.urlParams.flightNumber);
            
        });
        this.locationService.location.subscribe((location) => {
            // set default state only if user permitted geo position
            // search and filter isn't filled
            if (location && !this.flightNumber) {
                this.setDefaultState();
            }
        });
    }

    ngOnDestroy() {
    }

    get flightNumber() {
        return this.state.flightNumber;
    }

    set flightNumber(flightNumber: string) {
        this.state.flightNumber = flightNumber;
        if (flightNumber.length >= 4 && /^\d\d\d\d/.test(flightNumber)) {
            var date = new Date();
            date.setUTCHours(0,0,0,0);
            date.setDate(date.getDate() - 1);
            this.apiService
                .getFlightDaysByNumber(date, flightNumber)
                .then((res) => {
                    this.disabledDates = new Array();
                    for(var i=0;i<res.days.length;i++) {
                        if (res.days[i] == '0') {
                            this.disabledDates.push(new Date(date));
                        }
                        date.setDate(date.getDate() + 1);
                    }
                })
                .finally(() => {
                });
        } else {
            this.disabledDates = new Array();
        }  
    }

    get suffix() {
        return this.state.suffix;
    }

    set suffix(suffix: string) {
        this.state.suffix = suffix;
    }

    get date() {
        return this.state.flightNumberDate;
    }

    set date(date: Date) {
        this.state.flightNumberDate = date;
    }

    addZeros() {
        this.flightNumber = this.flightNumber.padStart(4, '0').toUpperCase();
        if (this.flightNumber.slice(-1)[0] > '9') {
            this.flightNumber = this.flightNumber.padStart(5, '0');
        }
    }

    clearInput() {
        this.flightNumber = undefined;
    }

    async search() {
        const params = this.getSearchParams();
        const areParamsValid = this.validationService.validate(params);
        if (!areParamsValid) {
            return;
        }
        this.stateService.set("boardnumber", params);

        this.onSearch.emit(params);
    }

    private setState(params: IParsedFlightId) {
        // uncomment in the following line if want to use 123D instead of 0123D
        this.flightNumber = (params.flightNumber+params.suffix).slice(/*+params.flightNumber > 999 ?*/ -5 /*: -4*/);
        this.date = params.date;
        this.suffix = params.suffix;
    }

    private setDefaultState() {
        this.date = new Date();
    }

    private getSearchParams(): IParsedFlightId {
        const suffix = this.flightNumber.length > 0 && this.flightNumber.slice(-1)[0] > '9' ? this.flightNumber.slice(-1) : "";
        const flightNumber = (suffix.length > 0) ? this.flightNumber.slice(0,-1) : this.flightNumber;

        return {
            flightNumber: flightNumber,
            date: this.date,
            carrier: 'SU',
            suffix: suffix,
        };
    }
}
