import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { ConfigService } from '@shared/config/config.service';
import { Router } from '@angular/router';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
import { MatDialog } from '@angular/material/dialog';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  ChangeUserRolesDialogComponent
} from '@shared/common-dialogs/clients-users/clients/change-user-roles-dialog/change-user-roles-dialog.component';
import { AuthService } from '@shared/auth/auth.service';
import { LineDirection, LineType } from '@objects-view/status-line/status-line.component';
import { StatusValue } from '@objects-view/interfaces/object-status';
import {
  AssociateUserDialogComponent
} from '@shared/common-dialogs/clients-users/clients/associate-user-dialog/associate-user-dialog.component';

@Component({
  selector: 'app-client-details-users',
  templateUrl: './client-details-users.component.html',
  styleUrls: ['./client-details-users.component.scss']
})
export class ClientDetailsUsersComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  users: IUserModel[];
  displayedColumns: string[];

  usersActions = {};
  protected readonly LineType = LineType;
  protected readonly LineDirection = LineDirection;

  constructor(
    private clientsApi: ClientsApiService,
    public config: ConfigService,
    private router: Router,
    private matDialog: MatDialog,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
    public auth: AuthService,
  ) {
    super(ngZone, changeDetectorRef, config);
    if (this.auth.feature('clients&users.roles')) {
      this.displayedColumns = ['user', 'roles', '(actions)'];
    } else {
      this.displayedColumns = ['user', '(actions)'];
    }
  }

  ngOnInit() {
    super.ngOnInit();
  }

  protected refreshData() {
    this.clientsApi.getUsers(this.object.id).subscribe(users => {
      this.users = users.users;
      this.usersActions = {};
      for (const user of this.users) {
        this.usersActions[user.id] = this.getUserActions(user);
        (user as any).statusValue = user.is_active ? StatusValue.Active : StatusValue.Error;
      }
    });
  }

  getUserActions(user: IUserModel): IAction[] {
    return [
      new RouterLinkAction({
        icon: {name: 'face'},
        tooltip: 'Impersonate user',
        name: 'Impersonate user',
        routerUrl: this.config.getPanelUrl(`clients-users/users/${user.id}/impersonate/${this.object.id}`),
        router: this.router,
      }),
      new CallbackAction({
        featureName: 'clients&users.roles',
        object: this.object,
        icon: {name: 'rule'},
        tooltip: 'Edit roles',
        name: 'Edit roles',
        callback: () => this.matDialog.open(
          ChangeUserRolesDialogComponent, {
            data: {client: this.object, user, existingRoles: user.roles},
            autoFocus: false,
          }).afterClosed().pipe(map(result => {
          if (result === false) {
            return;
          }
          this.refreshData();
          return {message: result} as IActionResult;
        }))
      }),
      new ApiCallAction({
        icon: {name: 'link_off'},
        tooltip: $localize`Dissociate user`,
        name: $localize`Dissociate user`,
        confirmOptions: {
          confirm: true,
          title: $localize`Dissociate user`,
          message: $localize`Are you sure you want to dissociate user ${user.display}?`,
        },
        object: this.object,
        apiService: this.clientsApi,
        callType: CallType.Post,
        apiAction: 'dissociate_user',
        apiParams: {
          id: this.object.id,
          user_id: user.id,
        },
        postExecuteCallback: () => {
          this.refreshData();
        },
      }),
    ];
  }

  associateNewUser() {
    this.matDialog.open(
      AssociateUserDialogComponent, {
        data: {
          client: this.object,
          associatedUsers: this.users,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.refreshData();
      }
    });
  }
}
