import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { UntypedFormBuilder } from '@angular/forms';
import { UserGroupsApiService } from '@fleio-api/client-user/user-group/user-groups-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { PermissionsSetsApiService } from '@fleio-api/core/permissions/permissions-sets-api.service';
import { IRoleModel } from '@fleio-api/client-user/roles/model/role.model';
import { IRolePermissionsModel } from '@fleio-api/core/permissions/model/role-permissions.model';

@Component({
  selector: 'app-role-details-permissions',
  templateUrl: './role-details-permissions.component.html',
  styleUrls: ['./role-details-permissions.component.scss']
})
export class RoleDetailsPermissionsComponent
  extends DetailsComponentBase<IRoleModel> implements OnInit, OnDestroy {
  rolePermissionsForm = this.formBuilder.group({});
  rolePermissions: IRolePermissionsModel;
  loading = false;
  editPermissions = false;

  constructor(private formBuilder: UntypedFormBuilder, private userGroupsApiService: UserGroupsApiService,
              private notificationService: NotificationService,
              private permissionsSetsApiService: PermissionsSetsApiService,
  ) {
    super();
  }

  refreshAllPermissions() {
    if (this.object?.id) {
      this.loading = true;
      this.permissionsSetsApiService.rolePermissions(this.object.id).subscribe(rolePermissions => {
        this.rolePermissions = rolePermissions;
      }).add(() => {
        this.loading = false;
      });
    }
  }

  showPermissionOptions() {
    return this.rolePermissions?.permissions;
  }

  saveRolePermissions() {
    this.loading = true;
    // get permissions out of categories
    const permissionsToBeSaved = JSON.parse(JSON.stringify(this.rolePermissions));
    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.saveRolePermissions(permissionsToBeSaved).subscribe(() => {
      this.notificationService.showMessage($localize`Role permissions saved`);
    }, error => {
      this.notificationService.showMessage(error.error.detail);
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.authSvc.feature('ui.clients&users.roles.edit-non-owned')) {
      this.editPermissions = true;
    } else {
      this.editPermissions = !!this.object?.owner;
    }

    this.editPermissions = this.editPermissions && !this.object?.default;

    this.refreshAllPermissions();
  }
}
