import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { ListViewEventData } from 'nativescript-ui-listview';
import { Observable } from 'rxjs';
import { transitionOptions } from '~/constants/shared.constants';
import { EvaluationSearch } from '../../entities/evaluation-search';
import { EvaluationAllUnitOutput } from '../../entities/output/evaluationAllUnitOutput';
import { SetSearchEvaluationDetailID } from '../../state-mgmt/evaluation-detail.actions';
import { LoadUnitEvaluations } from '../../state-mgmt/evaluation-list.actions';
import { SearchEvaluationListState } from '../../state-mgmt/evaluation-list.state';

@Component({
    selector: 'EvaluationList',
    moduleId: module.id,
    templateUrl: './evaluation-list.component.html',
    styleUrls: ['./evaluation-list.component.scss']
})

export class EvaluationListComponent implements OnInit {
    @Select(SearchEvaluationListState.isLoading) isLoading$: Observable<boolean>;
    @Select(SearchEvaluationListState.getEvaluations) searchEvaluations$: Observable<EvaluationAllUnitOutput[]>;
    @Select(SearchEvaluationListState.getSearchEvalParams) searchEvalParams$: Observable<EvaluationSearch>;

    othersIsLoading: boolean;
    searchEvaluations: EvaluationAllUnitOutput[];

    year: string;
    state: string;
    unit: string;

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private store: Store
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (this.router.url === '/evaluation/list') {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadUnitEvaluations());
        this.searchEvaluations$.subscribe(searchEvaluations => this.searchEvaluations = searchEvaluations);

        this.searchEvalParams$.subscribe(searchEvalParams => {
            this.year = searchEvalParams.getYearDisplay();
            this.state = searchEvalParams.getStateDisplay();
            this.unit = searchEvalParams.getUnitDisplay();
        });
    }

    // Routes on detail of item
    onItemTap(event: ListViewEventData) {
        const ID = this.searchEvaluations[event.index].ID;
        this.othersIsLoading = true;
        this.store.dispatch(new SetSearchEvaluationDetailID(ID));

        setTimeout(() => {
            this.routerExtensions.navigate(['evaluation/list', ID], { transition: transitionOptions });
        }, 10);
    }

    // Back button action
    onBackButton(): void {
        this.routerExtensions.back();
    }
}
