import { Pipe, PipeTransform } from '@angular/core';
import { ApplicationSettings } from '@nativescript/core';
import { wsUserManagement } from '~/constants/api.constants';
import { USER_ID, USER_TOKEN } from '~/constants/login-constants';
import { UserRoleAll } from '~/core/entities/input/userRoleAll';
import { UserRoleAllOutput } from '~/core/entities/output/userRoleAllOutput';
import { WebApiService } from '~/core/services/web-api.service';

/**
 * convert role id to role name promise
 * Therefore is needed use asnyc pipe after
 *
 * Usage:
 *   value | roleName
 * Example:
 *   {{ 2962 | roleName | async }}
 *   return 'role kopřivide'
 */
@Pipe({ name: 'roleName' })
export class RoleNamePipe implements PipeTransform {
    constructor(private webApiSrv: WebApiService) {
    }

    async transform(value: string) {
        let userRole;
        const userRoleAll = new UserRoleAll();

        userRoleAll.ID_Login = ApplicationSettings.getString(USER_TOKEN);
        userRoleAll.ID_User = ApplicationSettings.getNumber(USER_ID);

        if (userRoleAll.ID_Login && userRoleAll.ID_User) {
            try {
                const userRoles = await this.webApiSrv.call(userRoleAll, () => new UserRoleAllOutput(), wsUserManagement).toPromise();
                userRole = userRoles.find(uRole => uRole.ID === value);
            } catch (e) {
                console.error(e);
            }
        }

        return (userRole && userRole.DisplayName) || value;
    }
}
