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';

// TODO: somehow mail change triggered

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

  users: UserModel[] = [];
  newUser: UserModel | null = null;
  newUserPass = '';

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

  ngOnInit(): void {
    this.api.get<UserModel[]>('/users', data => {
      this.users = data.map(e => new UserModel().deserialize(e));
    });
  }

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

  saveNewUser() {
    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, username) {
    this.modal.open(modal).then(result => {
      if (result) {
        this.api.delete('/user/' + username, () => {
          this.users.splice(this.users.findIndex(e => e.name === username), 1);
        });
      }
    });
  }

}
