import { Component, OnInit } from '@angular/core';
import {DataService} from '../services/data.service';
import {ModelItemModel} from '../models/model-item.model';
import {ApiService} from '../services/api.service';
import {AutocompleteService} from '../services/autocomplete.service';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';

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

  newModel = false;
  modelGroup = '';
  oldModelGroup = '';
  oldModelName = '';
  model = new ModelItemModel().models[0];
  groups = [];

  constructor(
    private api: ApiService,
    public autocomplete: AutocompleteService,
    public d: DataService,
    private modal: ModalService
  ) { }

  ngOnInit(): void {
    this.loadGroups();
  }

  loadGroups() {
    delete this.d.arr.modelGroups;
    this.d.load('modelGroups', () => {
      this.groups = this.d.arr.modelGroups.map(e => e.group);
    });
  }

  saveModel() {
    console.log(this.modelGroup);
    console.log(this.oldModelGroup);
    if (this.oldModelGroup !== '' && this.modelGroup !== this.oldModelGroup) {  // group was changed, delete model in old group
      this.deleteModel(this.oldModelGroup, this.oldModelName);
    }
    this.api.post('/model/' + this.modelGroup, this.model, () => {
      this.newModel = false;
      this.loadGroups();
      this.modelGroup = '';
      this.oldModelGroup = '';
      this.oldModelName = '';
      this.model = new ModelItemModel().models[0];
      this.groups = this.d.arr.modelGroups.map(e => e.group);
    });
  }

  deleteModel(group, name, modal = null) {
    new Promise(resolve => {
      if (modal) {
        this.modal.open(modal).then(result => {
          resolve(result);
        });
      }
      else {
        resolve(true);
      }
    }).then(res => {
      if (res) {
        this.api.delete(`/model/${group}/${name}`, () => {
          this.loadGroups();
        });
      }
    });
  }

}
