import { Component } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { ConfigService } from '@shared/config/config.service';
import { IUserPermissionsModel } from '@fleio-api/core/permissions/model/user-permissions.model';
import { PermissionsSetsApiService } from '@fleio-api/core/permissions/permissions-sets-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-user-details-permissions',
  templateUrl: './user-details-permissions.component.html',
  styleUrl: './user-details-permissions.component.scss'
})
export class UserDetailsPermissionsComponent extends DetailsComponentBase<IUserModel> {
  userPermissions: IUserPermissionsModel;
  loading = false;

  constructor(
    private permissionsSetsApiService: PermissionsSetsApiService,
    private notificationService: NotificationService,
    public config: ConfigService,
  ) {
    super();
  }

  reloadEffectivePermissions() {
    this.objectController.loading = true;
    this.permissionsSetsApiService.userPermissions(this.object.id).subscribe(response => {
      this.userPermissions.effective_permissions = response.effective_permissions;
    }).add(() => {
      this.objectController.loading = false;
    });
  }

  protected tabActivated() {
    super.tabActivated();
    this.loading = true;
    this.permissionsSetsApiService.userPermissions(this.object.id).subscribe(response => {
      this.userPermissions = response;
    }).add(() => {
      this.loading = false;
    });
  }

  saveUserPermissions() {
    this.objectController.loading = true;
    // get permissions out of categories
    const permissionsToBeSaved = JSON.parse(JSON.stringify(this.userPermissions));
    const permissionsList = [];
    for (const panelKey of Object.keys(permissionsToBeSaved.permissions)) {
      for (const categoryKey of Object.keys(permissionsToBeSaved.permissions[panelKey])) {
        for (const permission of permissionsToBeSaved.permissions[panelKey][categoryKey]) {
          permissionsList.push(permission);
        }
      }
      permissionsToBeSaved.permissions[panelKey] = permissionsList;
    }
    this.permissionsSetsApiService.saveUserPermissions(permissionsToBeSaved).subscribe({
      next: () => {
        this.reloadEffectivePermissions();
        this.notificationService.showMessage($localize`User permissions saved`);
      }, error: error => {
        this.notificationService.showMessage(error.error.detail);
        this.objectController.loading = false;
      }
    });
  }

}
