import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { MenuElement } from 'src/app/model/view/menu-element';
import { AuthService } from 'src/app/service/auth.service';
import { PermissionsEnum } from 'src/app/model/auth/permissionsEnum';

@Injectable({
  providedIn: 'root',
})
export class SidebarService {
  visible$ = new BehaviorSubject<boolean>(true);
  elements$ = new BehaviorSubject<MenuElement[]>([]);

  constructor(private auth: AuthService) {
    this.auth.user$.subscribe(user => {
      if (user) {
        this.setElements().then();
      }
    });
  }

  show() {
    this.visible$.next(true);
  }

  hide() {
    this.visible$.next(false);
  }

  // trust me, you'll need this async
  async setElements() {
    const elements: MenuElement[] = [
      {
        label: 'common.domains',
        icon: 'pi pi-sitemap',
        routerLink: ['/admin/domains'],
        visible: await this.auth.hasAnyPermissionLazy([
          PermissionsEnum.domains,
        ]),
      },
      {
        label: 'common.groups',
        icon: 'pi pi-tags',
        routerLink: ['/admin/groups'],
        visible: await this.auth.hasAnyPermissionLazy([PermissionsEnum.groups]),
      },
      {
        label: 'common.urls',
        icon: 'pi pi-tag',
        routerLink: ['/admin/urls'],
        visible: await this.auth.hasAnyPermissionLazy([
          PermissionsEnum.shortUrls,
          PermissionsEnum.shortUrlsByAssignment,
        ]),
      },
      await this.groupAdministration(),
    ];
    this.elements$.next(elements);
  }

  async groupAdministration() {
    return {
      label: 'sidebar.administration',
      icon: 'pi pi-wrench',
      expanded: true,
      visible: await this.auth.hasAnyPermissionLazy([
        PermissionsEnum.users,
        PermissionsEnum.roles,
        PermissionsEnum.apiKeys,
      ]),
      items: [
        {
          label: 'sidebar.users',
          icon: 'pi pi-user',
          routerLink: ['/admin/administration/users'],
          visible: await this.auth.hasAnyPermissionLazy([
            PermissionsEnum.users,
          ]),
        },
        {
          label: 'sidebar.roles',
          icon: 'pi pi-user-edit',
          routerLink: ['/admin/administration/roles'],
          visible: await this.auth.hasAnyPermissionLazy([
            PermissionsEnum.roles,
          ]),
        },
        {
          label: 'sidebar.api_keys',
          icon: 'pi pi-key',
          routerLink: ['/admin/administration/api-keys'],
          visible: await this.auth.hasAnyPermissionLazy([
            PermissionsEnum.apiKeys,
          ]),
        },
      ],
    };
  }
}
