import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IUserGroupModel } from '@fleio-api/client-user/model/user-group.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { PermissionsSetsApiService } from '@fleio-api/core/permissions/permissions-sets-api.service';
import { IGroupPermissionsModel } from '@fleio-api/core/permissions/model/group-permissions.model';

@Component({
  selector: 'app-user-group-details-permissions',
  templateUrl: './user-group-details-permissions.component.html',
  styleUrl: './user-group-details-permissions.component.scss'
})
export class UserGroupDetailsPermissionsComponent extends DetailsComponentBase<IUserGroupModel> implements OnInit {
  groupPermissions: IGroupPermissionsModel;
  loading = false;

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

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

  saveUserGroupPermissions() {
    this.objectController.loading = true;
    // get permissions out of categories
    const permissionsToBeSaved = JSON.parse(JSON.stringify(this.groupPermissions));
    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.saveGroupPermissions(permissionsToBeSaved).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`User group permissions saved`);
      }, error: error => {
        this.notificationService.showMessage(error.error.detail);
      }
    }).add(() => {
      this.objectController.loading = false;
    });
  }


}
