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 { ConfigService } from '@shared/config/config.service';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { map } from 'rxjs/operators';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AutocompleteHelper } from '@shared/ui-api/helpers/autocomplete-helper';

@Component({
  selector: 'app-user-group-details-overview',
  templateUrl: './user-group-details-overview.component.html',
  styleUrls: ['./user-group-details-overview.component.scss']
})
export class UserGroupDetailsOverviewComponent extends DetailsComponentBase<IUserGroupModel> implements OnInit {
  users: IUserModel[];
  userActions: { [id: number]: IAction[] };
  displayedColumns = ['id', 'email', 'full_name', '(actions)'];
  currentPage = 1;
  nextPage = false;
  previousPage = false;
  loading = false;

  userForm = this.formBuilder.group({
    user: [''],
  });
  customTxt = $localize`custom`;
  defaultTxt = $localize`default`;


  constructor(
    public config: ConfigService,
    private usersApiService: UsersApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.object) {
      this.loadUsers(this.currentPage);
    }
  }

  changePage(action: string) {
    if (action === 'next') {
      this.currentPage = this.currentPage + 1;
      this.loadUsers(this.currentPage);
    }
    if (action === 'previous') {
      this.currentPage = this.currentPage - 1;
      this.loadUsers(this.currentPage);
    }
  };

  loadUsers(page: number) {
    this.loading = true;
    this.usersApiService.getUsersInGroup(this.object.id, page).subscribe(response => {
      this.users = response.objects;
      this.userActions = {};
      for (const user of this.users) {
        this.userActions[user.id] = this.getUserActions(user);
      }

      this.nextPage = !!response.next;
      this.previousPage = !!response.previous;
      this.loading = false;
    });
  }

  getUserActions(user: IUserModel): IAction[] {
    return [
      new CallbackAction({
        icon: {name: 'link_off'},
        tooltip: $localize`Remove user from group`,
        name: $localize`Remove user from group`,
        displayMessages: false,
        confirmOptions: {
          confirm: true,
          title: $localize`Remove user from group`,
          message: $localize`Are you sure you want to remove user ${user.display} from group?`,
        },
        refreshAfterExecute: true,
        callback: () => this.usersApiService.removeFromGroup(user.id, this.object.id).pipe(map(() => {
            this.loadUsers(this.currentPage);
            AutocompleteHelper.refreshAutocompleteOptions(this.userForm.controls.user);
            return null;
          }))
      }),
    ];
  }

  addUserToGroup() {
    const user = this.userForm.controls.user.value as IUserModel;
    this.objectController.loading = true;
    this.usersApiService.addToGroup(user.id, this.object.id).subscribe(
      (response) => {
        this.loadUsers(this.currentPage);
        this.userForm.controls.user.setValue('');
        this.notificationService.showMessage(response.detail);
      },
      () => {
        this.notificationService.showMessage($localize`Failed to add user to group`);
      }
    ).add(() => {
      this.objectController.loading = false;
    });
  }
}
