import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { ConfigService } from '@shared/config/config.service';
import { IUserGroupModel } from '@fleio-api/client-user/model/user-group.model';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { MatDialog } from '@angular/material/dialog';
import { AddUserToGroupDialogComponent } from './add-user-to-group-dialog/add-user-to-group-dialog.component';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { NotificationService } from '@shared/ui-api/notification.service';
import { CallbackAction } from '@objects-view/actions/callback-action';

@Component({
  selector: 'app-user-details-groups',
  templateUrl: './user-details-groups.component.html',
  styleUrls: ['./user-details-groups.component.scss']
})
export class UserDetailsGroupsComponent extends DetailsComponentBase<IUserModel> implements OnInit {
  invoices: IInvoiceModel[];
  displayedColumns: string[] = ['id', 'name', '(actions)'];
  userGroups: Array<IUserGroupModel> = null;

  userGroupActions: {
    [userGroupId: number]: [];
  } = {};

  getUserGroupActions(userGroupId) {
    return [
      new CallbackAction({
        object: this.object,
        icon: {name: 'link_off'},
        tooltip: $localize`Remove from group`,
        name: $localize`Remove from group`,
        callback: action => this.removeUserFromGroup(userGroupId)
        }
      ),
    ];
  }

  removeUserFromGroup(userGroupId: FleioId) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`This will remove the user from the group`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.usersApiService.removeFromGroup(this.object.id, userGroupId).pipe(map(success => {
          if (success) {
            this.notificationService.showMessage($localize`User removed from group.`);
            this.refreshData();
          } else {
            this.notificationService.showMessage($localize`Could not remove user from group.`);
          }
        })).subscribe();
      }
    });
    return of(null);
  }

  addToGroup() {
    this.matDialog.open(
      AddUserToGroupDialogComponent, {
        data: {user: this.object},
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.refreshData();
      }
    });
  }

  protected refreshData() {
    this.usersApiService.get(this.object.id).subscribe(user => {
      this.objectController.object = user;
      this.updateUserGroups();
    });
  }

  constructor(
    public config: ConfigService,
    private usersApiService: UsersApiService,
    private matDialog: MatDialog,
    private notificationService: NotificationService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef , config);
  }

  updateUserGroups() {
    if (this.object) {
      this.userGroups = this.object.user_groups;
      for (const group of this.userGroups) {
        this.userGroupActions[group.id] = this.getUserGroupActions(group.id);
      }
    }
  }

  ngOnInit() {
    super.ngOnInit();
    this.updateUserGroups();
  }
}
