import { Component, OnInit } from '@angular/core';
import {ApiService} from '../services/api.service';
import {UserModel} from '../models/user.model';
import {LoginService} from '../services/login.service';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
import {DataService} from '../services/data.service';


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

  users: UserModel[] = [];           // all active users
  deletedUsers: UserModel[] = [];    // all deleted users
  newUser: UserModel | null = null;  // data of new user
  newUserPass = '';                  // password of new user
  modelSelect: {id: string, name: string}[] = [];  // list of all models for selection
  modelIds: {[id: string]: string} = {};           // all models by id

  constructor(
    private api: ApiService,
    public login: LoginService,
    private modal: ModalService,
    public d: DataService
  ) { }

  ngOnInit(): void {
    this.api.get<UserModel[]>('/users', data => {
      this.users = data.map(e => new UserModel().deserialize(e)).filter(e => e.status !== 'deleted');
      this.deletedUsers = data.map(e => new UserModel().deserialize(e)).filter(e => e.status === 'deleted');
    });
    this.d.load('modelGroups', () => {
      this.d.arr.modelGroups.forEach(group => {
        this.modelSelect.push(...group.models.map(e => ({id: e._id, name: `${group.group} - ${e.name}`})));
      });
      this.modelIds = this.modelSelect.reduce((s, e) => {s[e.id] = e.name; return s; }, {});
    });
  }

  saveUser(user: UserModel) {
    user.models = user.models.filter(e => e !== '');
    this.api.put<UserModel>('/user/' + user.origName, user.sendFormat('admin'), data => {
      user.deserialize(data);
      user.edit = false;
    });
  }

  saveNewUser() {
    this.newUser.models = this.newUser.models.filter(e => e !== '');
    this.api.post('/user/new', {...this.newUser.sendFormat('admin'), pass: this.newUserPass}, data => {
      this.newUser = null;
      this.users.push(new UserModel().deserialize(data));
      this.newUserPass = '';
    });
  }

  addNewUser() {
    this.newUser = this.newUser ? null : new UserModel();
  }

  deleteConfirm(modal, user) {
    this.modal.open(modal).then(result => {
      if (result) {
        this.api.delete('/user/' + user.name, () => {
          user.status = 'deleted';
          user.edit = false;
          this.deletedUsers.push(user);
          this.users.splice(this.users.findIndex(e => e.name === user.name), 1);
        });
      }
    });
  }

  restoreUser(user) {
    this.api.put('/user/restore/' + user.name, {}, () => {
      user.status = 'new';
      this.users.push(user);
      this.deletedUsers.splice(this.deletedUsers.findIndex(e => e.name === user.name), 1);
    });
  }
}
