import {Component, OnInit} from '@angular/core';
import {StringHelper} from '../../helpers/string-helper';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {GridApi} from 'ag-grid-community';
import {LookupSourceService} from '../../logic/services/lookup-source.service';
import {AlertService} from '../../ui/infrastructure/alert.service';
import {FormHelper} from '../../ui/controls/form-helper';
import {SecurityService} from '../../logic/services/security.service';

@Component({
  selector: 'app-list-users',
  templateUrl: './list-users.component.html',
  styleUrls: ['./list-users.component.css']
})
export class ListUsersComponent implements OnInit {

  contextFormGroup: FormGroup;
  rowData = [];
  isLoading = false;
  gridApi: GridApi;

  editUserModalOpened = false;

  public rolesCaption = {};

  public defaultColDef = {
    sortable: true,
    filter: true,
    resizable: true
  };

  gridColumnDefs = [
    {
      headerName: 'ID',
      field: 'id'
    },
    {
      headerName: 'Роль',
      field: 'roleId',
      cellRenderer: params =>
        this.rolesCaption[params.data.roleId] ? this.rolesCaption[params.data.roleId] : '',
    },
    {
      headerName: 'Фамилия',
      field: 'lastName'
    },
    {
      headerName: 'Имя',
      field: 'firstName'
    },
    {
      headerName: 'Отчество',
      field: 'middleName'
    },
    {
      headerName: 'Логин',
      field: 'username'
    }];

  private static buildForm(fb: FormBuilder, data: any) {
    return fb.group({
      id: data.id,
      username: [data.username ? data.username : '', Validators.required],
      password: ['', Validators.required],
      lastName: [data.lastName ? data.lastName : '', Validators.required],
      firstName: data.firstName ? data.firstName : '',
      middleName: data.middleName ? data.middleName : '',
      roleId: [data.roleId ? data.roleId : null, Validators.required]
    });
  }

  constructor(private fb: FormBuilder,
              public securityService: SecurityService,
              private alertService: AlertService,
              private lookupService: LookupSourceService) {

    // subscribe в грид не засунешь, поэтому на стадии создания компонента
    // создадим временный объект
    this.lookupService.getLookup('security/security-roles')
        .subscribe(roles =>
          roles.forEach(role => this.rolesCaption[role.id] = role.caption));
  }

  onGridReady(params) {
    this.gridApi = params.api;
  }

  ngOnInit() {
    this.loadData();
  }

  refreshFormData() {
    this.loadData();
  }

  loadData() {
    this.isLoading = true;
    this.rowData = [];
    this.securityService.getListUsers()
      .subscribe(users => this.setData(users));
  }

  setData(data: any) {
    this.rowData = data;
    this.isLoading = false;
  }

  onGridSizeChanged (params) {
    const gridWidth = params.clientWidth;
    const allColumns = params.columnApi.getAllGridColumns();

    allColumns.forEach((col, index) => {
      params.columnApi.setColumnWidth(col, index === 0 ? gridWidth * 0.05 : gridWidth * 0.189);
    });
  }

  isInvalid(controlName: string): boolean {
    return FormHelper.isInvalid(this.contextFormGroup, controlName);
  }

  createNewUser() {
    this.contextFormGroup = ListUsersComponent.buildForm(this.fb, {});
    this.editUserModalOpened = true;
  }

  editUser($event: any) {
    this.contextFormGroup = ListUsersComponent.buildForm(this.fb, $event.data);
    this.editUserModalOpened = true;
  }

  storeUser(data: any) {
    return this.securityService.storeUser(data)
      .subscribe(ok => {
        this.alertService.success('Пользователь сохранен');
        this.closeModal();
        this.loadData();
      });
  }

  deleteUser(user: any) {
    this.alertService.confirmModal('Вы уверены, что хотите удалить пользователя?', 'Да')
      .subscribe(confirm => {
        if (confirm) {
          this.securityService.deleteUser(user).subscribe({
            next: () => {
              this.alertService.success('Пользователь удален');
              this.closeModal();
              this.loadData();
            },
            error: () => {
              this.alertService.error('Не удалось удалить пользователя');
            }
          });
        }
      });
  }

  closeModal() {
    this.contextFormGroup = null;
    this.editUserModalOpened = false;
  }
}
