import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { ApplicationSettings, ImageSource } from '@nativescript/core';
import { action } from '@nativescript/core/ui/dialogs';
import { Select, Store } from '@ngxs/store';
import { ListViewEventData } from 'nativescript-ui-listview';
import { Observable } from 'rxjs';
import { APP_ID, wsUserManagement } from '~/constants/api.constants';
import { USER_ID, USER_ROLE, USER_ROLE_ID, USER_TOKEN, USER_UNIT_ID } from '~/constants/login-constants';
import { transitionOptions } from '~/constants/shared.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 { WebApiService } from '~/core/services/web-api.service';
import {
    LoadMessageAllWebUnread,
    LoadPersonPhoto,
    StartRoleLoading,
    StopRoleLoading
} from '~/core/state-mgmt/app.actions';
import { AppState } from '~/core/state-mgmt/app.state';
import { AdvertisingAllowedFunctionTypes } from '~/pages/advertising/utils/allowedAdvertisingFunctionTypes';
import { ApplicationAllowedFunctionTypes } from '~/pages/application/utils/allowedApplicationFunctionTypes';
import { MaterialAllowedFunctionTypes } from '~/pages/material/utils/allowedMaterialFunctionTypes';

@Component({
    selector: 'Home',
    moduleId: module.id,
    templateUrl: './profile.component.html',
    styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {
    @Select(AppState.getPersonPhotoResource) personPhotoResource$: Observable<ImageSource>;
    @Select(AppState.getMessageAllWebUnread) messagesUnread$: Observable<MessageAllWebOutput[]>;
    @Select(AppState.isLoading) isLoading$: Observable<boolean>;
    isLoading: boolean;
    othersIsLoading: boolean;
    roleDialogOpen = false;
    userData: any = null;
    personPhotoResource: ImageSource = null;
    messagesUnread: MessageAllWebOutput[];

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

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

        this.loginDataSrv.updateUserData();
        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();
        });

        this.personPhotoResource$.subscribe((personPhotoResource: ImageSource) => this.personPhotoResource = personPhotoResource);

        this.messagesUnread$.subscribe((messagesUnread: MessageAllWebOutput[]) => {
            this.messagesUnread = messagesUnread;
        });

        this.isLoading$.subscribe(isLoading => {
            setTimeout(() => {
                this.isLoading = isLoading;
            });
        });
    }

    async onUserRoleTap() {
        this.store.dispatch(new StartRoleLoading());
        const userRoleAll = new UserRoleAll(APP_ID, ApplicationSettings.getString(USER_TOKEN), ApplicationSettings.getNumber(USER_ID));
        let userRoleAllOutput: UserRoleAllOutput[] = [];
        try {
            userRoleAllOutput = await this.webApiSrv.call(userRoleAll, () => new UserRoleAllOutput(), wsUserManagement).toPromise();
        } catch (e) {
            console.error(e);
        }
        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, ApplicationSettings.getString(USER_TOKEN), role.key);
                    let logUpdOut: LoginUpdateOutput[] = [];
                    try {
                        logUpdOut = await this.webApiSrv.call(loginUpdateRole, () => new LoginUpdateOutput(), wsUserManagement).toPromise();
                    } catch (e) {
                        console.error(e);
                    }
                    setTimeout(() => {
                        ApplicationSettings.setNumber(USER_ROLE_ID, role.key);
                        ApplicationSettings.setString(USER_ROLE, role.label);
                        if (logUpdOut.length > 0) {
                            ApplicationSettings.setNumber(USER_UNIT_ID, logUpdOut[0].ID_Unit);
                            MaterialAllowedFunctionTypes.setPermission(role.label);  // Material page allowing
                            ApplicationAllowedFunctionTypes.setPermission(role.label);  // Application page allowing
                            AdvertisingAllowedFunctionTypes.setPermission(role.label);
                        }
                        this.loginDataSrv.updateUserData();
                    });
                }
                this.roleDialogOpen = false;
            });
        }
    }

    onNavTap(navRoute: string): void {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate([navRoute],
                { transition: transitionOptions });
        }, 10);
    }

    onItemTap(event: ListViewEventData) {
        setTimeout(() => {
            this.routerExtensions.navigate(['message/list', this.messagesUnread[event.index].ID],
                { transition: transitionOptions });
        }, 10);
    }


    templateSelector(item: any, index: number, items: any): string {
        return 'default';
    }

    onPhotoTap(userId: number): void {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['search/list/', userId, false],
                { transition: transitionOptions });
        }, 10);
    }
}
