import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { ConfigService } from '@shared/config/config.service';
import { IObjectUIService } from '@objects-view/interfaces/object-ui-service';
import { ITableData } from '@objects-view/interfaces/table-data/table-data';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ITableRow } from '@objects-view/interfaces/table-data/table-row';
import { ColumnType } from '@objects-view/interfaces/table-data/column-definition';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { UserUIService } from './user-ui.service';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { AuthService } from '@shared/auth/auth.service';

@Injectable({
  providedIn: 'root',
})
export class UserListUIService implements IObjectListUIService {
  public noItemsMessage = $localize`No users`;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    private router: Router,
    private config: ConfigService,
    private usersApi: UsersApiService,
    private auth: AuthService,
  ) {
    this.datePipe = new DateFormatterPipe(config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new UserUIService(
      object as IUserModel, permissions, state, this.router, this.config, this.usersApi, this.auth,
    );
  }

  getTableData(objectList: FleioObjectsList<IUserModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Image, displayName: '', enableSort: false, fieldName: '(image)',
            flex: '50px',
          },
          {
            type: ColumnType.Value, displayName: $localize`ID`, enableSort: false, fieldName: 'id',
            flex: '60px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Full name`, enableSort: false, fieldName: 'full_name',
            flex: '1 0 100px', flexXs: '1 0 150px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Email`, enableSort: true, fieldName: 'email',
            flex: '200px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Last login`, enableSort: true, fieldName: 'last_login',
            hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`User labels`, enableSort: true, fieldName: 'labels',
            hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
          },
        ],
        columnNames: ['(image)', 'id', 'full_name', 'email', 'last_login', 'labels', '(actions)'],
        showStatus: true,
      },
      rows: [],
    };

    for (const object of objectList.objects) {
      const rowUIService = this.getObjectUIService(object, objectList.permissions, 'table-view');
      const user = object as IUserModel;
      const labelsList = [];
      if (object.is_staff) {
        labelsList.push($localize`staff`);
      }
      if (object.is_superuser) {
        labelsList.push($localize`superuser`);
      }
      if (!object.is_active) {
        labelsList.push($localize`inactive`);
      }

      const row: ITableRow = {
        cells: {
          id: {text: user.id.toString()},
          full_name: {text: user.full_name},
          email: {text: user.email},
          last_login: {text: user.last_login ? this.datePipe.toDateTime(user.last_login) : $localize`never`},
          labels: {tags: labelsList}
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: user,
      };

      tableData.trackByFunction = (index, item: ITableRow) => item.object.id;
      tableData.rows.push(row);
    }

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return [
      new RouterLinkAction({
        name: $localize`Create new user`,
        tooltip: $localize`Create new user`,
        icon: {name: 'add'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('clients-users/users/create'),
        noPermissions: !objectList.permissions['users.create'],
      })
    ];
  }

  getRefreshInterval(): number {
    if (this.config && this.config.current && this.config.current.settings &&
      this.config.current.settings.refreshIntervals) {
      return this.config.current.settings.refreshIntervals.defaultInterval;
    }
    return 10000;
  }
}
