import { Component, OnInit } from '@angular/core';
import { PageRoute, RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { PickerProvider } from '~/core/entities/picker-provider';
import { EnrollNumberAllPersonOutput } from '~/pages/sts/entities/output/enrollNumberAllPersonOutput';
import { EnrollNumberAllUsageOutput } from '~/pages/sts/entities/output/enrollNumberAllUsageOutput';
import { LoadEnrollNumberUsages, LoadStatsEnrollNumbers } from '~/pages/sts/state-mgmt/sts-detail-stats.actions';
import { StsDetailStatsState } from '~/pages/sts/state-mgmt/sts-detail-stats.state';
import { Item } from '~/shared/components/item-picker/item';
import { PhonePipe } from '~/shared/pipes/phone.pipe';

@Component({
    selector: 'StsDetailStats',
    moduleId: module.id,
    templateUrl: './sts-detail-stats.component.html',
    styleUrls: ['./_sts-detail-stats.component.scss']
})
export class StsDetailStatsComponent implements OnInit {
    @Select(StsDetailStatsState.getEnrollNumberUsages) enrollNumberUsages$: Observable<EnrollNumberAllUsageOutput[]>;
    @Select(StsDetailStatsState.getStatsEnrollNumbers) statsEnrollNumbers$: Observable<EnrollNumberAllPersonOutput[]>;
    @Select(StsDetailStatsState.isLoading) isLoading$: Observable<boolean>;

    enrollNumberUsages: EnrollNumberAllUsageOutput[];
    statsEnrollNumbersForProvider: PickerProvider[];
    phoneNumber: string;
    phone: Item;

    constructor(
        private routerExtensions: RouterExtensions,
        private pageRoute: PageRoute,
        private phonePipe: PhonePipe,
        private store: Store
    ) {
    }

    /**
     * In NgInit hook take number from params and dispatch action for load enroll numbers
     * Too It subsribe enrollNumber data and crete data for Picker from that
     * and set selected number (if number from params is in subscribed data
     *
     * If is selected number then dispatch action number usages
     */
    ngOnInit() {
        this.statsEnrollNumbersForProvider = [];
        this.pageRoute.activatedRoute
            .pipe(
                switchMap(activatedRoute => activatedRoute.params)
            )
            .forEach((params) => {
                this.phoneNumber = params['number'];

                if (this.phoneNumber) {
                    this.store.dispatch(new LoadStatsEnrollNumbers());
                }
            });

        this.statsEnrollNumbers$.subscribe((enrollNumbers: EnrollNumberAllPersonOutput[]) => {
            this.statsEnrollNumbersForProvider = enrollNumbers.map((enrollNumber: EnrollNumberAllPersonOutput) => (
                new PickerProvider(enrollNumber.ID, `${this.phonePipe.transform(enrollNumber.DisplayName)}`)
            ));

            const selectedNumber = enrollNumbers.find((enrollNumber: EnrollNumberAllPersonOutput) => enrollNumber.DisplayName === this.phoneNumber);
            this.phone = selectedNumber ? new Item(selectedNumber.ID) : undefined;
        });
        this.enrollNumberUsages$.subscribe(enrollNumberUsages => this.enrollNumberUsages = enrollNumberUsages);
    }

    onSelectedPhone(phoneId: number | string) {
        if (!this.phone || this.phone.id !== phoneId) {
            this.phone = new Item(phoneId);
            if (this.phone && this.phone.id !== -1) {
                this.store.dispatch(new LoadEnrollNumberUsages(+this.phone.id));
            }
        }
    }

    onBackButton(): void {
        this.routerExtensions.back();
    }
}
