import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { ApplicationSettings } from '@nativescript/core';
import { Select, Store } from '@ngxs/store';
import { Observable, of } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { USER_ROLE_ID } from '~/constants/login-constants';
import { transitionOptions } from '~/constants/shared.constants';
import { UserRoleAllOutput } from '~/core/entities/output/userRoleAllOutput';
import { PickerProvider } from '~/core/entities/picker-provider';
import { AuthGuard } from '~/core/services/auth-guard.service';
import { LoadUserRoleAll } from '~/core/state-mgmt/app.actions';
import { AppState } from '~/core/state-mgmt/app.state';
import { EvaluationSearch } from '../../entities/evaluation-search';
import { SetSearchEvaluationParams } from '../../state-mgmt/evaluation-list.actions';
import { EvaluationUpdatePermission } from '../../state-mgmt/evaluation-permission.actions';
import { EvaluationPermissionState } from '../../state-mgmt/evaluation-permission.state';
import { LoadStates } from '../../state-mgmt/evaluation-states.actions';
import { StatesState } from '../../state-mgmt/evaluation-states.state';
import { LoadYears } from '../../state-mgmt/evaluation-years.actions';
import { YearsState } from '../../state-mgmt/evaluation-years.state';

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

export class EvaluationComponent implements OnInit {
    @Select(YearsState.getYearsForProvider) years$: Observable<PickerProvider[]>;
    @Select(StatesState.getStatesForProvider) states$: Observable<PickerProvider[]>;

    @Select(YearsState.isLoading) yearsIsLoading$: Observable<boolean>;
    @Select(StatesState.isLoading) statesIsLoading$: Observable<boolean>;

    @Select(AppState.getUserRoleAll) userRoleAll$: Observable<UserRoleAllOutput[]>;

    @Select(EvaluationPermissionState.hasPersonEvalPermission) isAllowedToPersonalEval: boolean;

    unit$: Observable<PickerProvider[]>;
    othersIsLoading: boolean;

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

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadYears());
        this.store.dispatch(new LoadStates());

        this.store.dispatch(new LoadUserRoleAll())
            .pipe(withLatestFrom(this.userRoleAll$))
            .subscribe(([_, result]) => {
                const role = result.find(role => role.ID === ApplicationSettings.getNumber(USER_ROLE_ID));
                if (role) {
                    this.store.dispatch(new EvaluationUpdatePermission(role.DisplayName));
                }
            });

        this.unit$ = of([
            new PickerProvider('MyUnit', 'Moje jednotka'),
            new PickerProvider('ChildUnits', 'Podřízené jednotky'),
            new PickerProvider('ParentUnits', 'Nadřízené jednotky')
        ]);
    }

    // Search button action
    onSearchEvaluation(evaluationSearch: EvaluationSearch) {
        this.othersIsLoading = true;
        this.authGuard.canActivate();
        this.store.dispatch(new SetSearchEvaluationParams(evaluationSearch));
        setTimeout(() => {
            this.routerExtensions.navigate(['/evaluation/list'], { transition: transitionOptions });
        }, 10);
        this.othersIsLoading = false;
    }

    // Create button action
    onCreate() {
        this.othersIsLoading = true;
        this.authGuard.canActivate();
        setTimeout(() => {
            this.routerExtensions.navigate(['/evaluation/create'], { transition: transitionOptions });
        }, 10);
        this.othersIsLoading = false;
    }
}
