import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { ImageSource } from '@nativescript/core/image-source';
import { action } from '@nativescript/core/ui/dialogs';
import { APP_ID, wsUserManagement } from '~/constants/api.constants';
import { USER_TOKEN, USER_ID, USER_ROLE_ID, USER_UNIT_ID, USER_ROLE } from '~/constants/login-constants';
import { LoginUpdate } from '~/core/entities/input/loginUpdate';
import { UserRoleAll } from '~/core/entities/input/userRoleAll';
import { LoginUpdateOutput } from '~/core/entities/output/loginUpdateOutput';
import { MessageAllWebOutput } from '~/core/entities/output/messageAllWebOutput';
import { UserRoleAllOutput } from '~/core/entities/output/userRoleAllOutput';
import { LoginDataService } from '~/core/services/login-data.service';
import { ApplicationSettings as AppSettings } from '@nativescript/core';
import { WebApiService } from '~/core/services/web-api.service';
import { LoadMessageAllWebUnread, StartRoleLoading, StopRoleLoading } from '~/core/state-mgmt/app.actions';
import { AppState } from '~/core/state-mgmt/app.state';
import { MaterialAllowedFunctionTypes } from '~/pages/material/utils/allowedMaterialFunctionTypes';
import { LoadPersonPhoto } from '~/pages/search-person/state-mgmt/search-person-detail.actions';
import { EnrollNumberAllPersonOutput } from '~/pages/sts/entities/output/enrollNumberAllPersonOutput';
import { LoadEnrollNumbers } from '~/pages/sts/state-mgmt/sts.actions';
import { StsState } from '~/pages/sts/state-mgmt/sts.state';
import { transitionOptions } from '~/constants/shared.constants';
import { RouterExtensions } from '@nativescript/angular';
import * as dialogs from "@nativescript/core/ui/dialogs";

@Component({
    selector: 'ProfilePage',
    moduleId: module.id,
    templateUrl: './profile-page.component.html',
    styleUrls: ['./_profile-page.component.scss']
})
export class ProfilePageComponent implements OnInit {
    @Select(AppState.isLoading)
    isLoading$: Observable<boolean>;
    @Select(AppState.getMessageAllWebUnread)
    messagesUnread$: Observable<MessageAllWebOutput[]>;
    @Select(AppState.getPersonPhotoResource)
    personPhotoResource$: Observable<ImageSource>;
    @Select(StsState.getEnrollNumbers) enrollNumbers$: Observable<EnrollNumberAllPersonOutput[]>;


    routeLoading: boolean;
    userData: any = null;
    messagesUnread: MessageAllWebOutput[];
    roleDialogOpen = false;

    constructor(
        private router: Router,
        private loginDataSrv: LoginDataService,
        private webApiSrv: WebApiService,
        private store: Store,
        private routerExtensions: RouterExtensions,
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (this.router.url === '/home/profile') {
                    this.routeLoading = false;
                }
            }
        });

    }

    refreshMessages() {
        this.store.dispatch(new LoadMessageAllWebUnread())
            .pipe(withLatestFrom(this.messagesUnread$)).subscribe(([_, msgs]) => {
                this.messagesUnread = msgs;
            });
    }

    ngOnInit(): void {
        this.routeLoading = false;
        this.roleDialogOpen = false;

        this.loginDataSrv.updateUserData();
        this.refreshMessages()

        this.store.dispatch(new LoadEnrollNumbers())

        this.userData = this.loginDataSrv.loginData.subscribe((data: any) => {
            this.userData = data;
            if (this.userData) {
                this.store.dispatch(new LoadPersonPhoto(this.userData.userId));
            }
        });
        setTimeout(() => {
            this.loginDataSrv.updateUserData();
        });
    }

    async onUserRoleTap() {
        this.store.dispatch(new StartRoleLoading());
        const userRoleAll = new UserRoleAll(APP_ID, AppSettings.getString(USER_TOKEN), AppSettings.getNumber(USER_ID));
        const userRoleAllOutput: UserRoleAllOutput[] = await this.webApiSrv.call(userRoleAll, () => new UserRoleAllOutput(), wsUserManagement).toPromise();
        const roles = userRoleAllOutput.map(obj => ({ key: obj.ID, label: obj.DisplayName }));

        const options = {
            message: 'Vyberte roli',
            cancelButtonText: 'Zrušit',
            actions: roles.map(obj => obj.label)
        };

        this.store.dispatch(new StopRoleLoading());

        if (!this.roleDialogOpen) {
            this.roleDialogOpen = true;
            action(options).then(async (result) => {
                const role = roles.find(obj => obj.label === result);
                if (role) {
                    const loginUpdateRole = new LoginUpdate(APP_ID, AppSettings.getString(USER_TOKEN), role.key);
                    const logUpdOut: LoginUpdateOutput[] = await this.webApiSrv.call(loginUpdateRole, () => new LoginUpdateOutput(), wsUserManagement).toPromise();
                    setTimeout(() => {
                        AppSettings.setNumber(USER_ROLE_ID, role.key);
                        AppSettings.setString(USER_ROLE, role.label);
                        if (logUpdOut.length > 0) {
                            AppSettings.setNumber(USER_UNIT_ID, logUpdOut[0].ID_Unit);
                            AppSettings.setString(USER_ROLE, role.label)
                            MaterialAllowedFunctionTypes.setPermission(role.label);  // Material page allowing
                        }
                        this.loginDataSrv.updateUserData();
                    });
                }
                this.roleDialogOpen = false;
            });
        }
    }
    routeChange(val) {
        this.routeLoading = val;
    }
    onLogOut(): void {
        const options = {
            title: "Odhlášení",
            message: `Opravdu se chcete odhlásit?`,
            okButtonText: "Ano",
            cancelButtonText: "Ne"
        };
        dialogs.confirm(options).then((result: boolean) => {
            if (result) {
                MaterialAllowedFunctionTypes.firstTimeRole = true;  // because of MAJETEK permission
                this.loginDataSrv.logout().then(() => {
                    this.routerExtensions.navigate(['/home'],
                        { clearHistory: true, transition: transitionOptions });
                })
            };
        });
    }

}
