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';
import omit from 'lodash/omit';

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

  newModel = false;    // display new model dialog
  modelGroup = '';     // group of the edited model
  oldModelGroup = '';  // group of the edited model before editing started
  oldModelName = '';   // name of the edited model before editing started
  model = new ModelItemModel().models[0];  // edited model
  groups = [];         // all model group names

  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);
    });
    this.d.load('modelFiles');
  }

  saveModel() {
    // group was changed, delete model in old group
    if (this.oldModelGroup !== '' && this.modelGroup !== this.oldModelGroup) {
      this.delete(null, this.oldModelName, this.oldModelGroup);
    }
    this.api.post('/model/' + this.modelGroup, omit(this.model, '_id'), () => {
      this.newModel = false;  // reset model edit parameters
      this.loadGroups();
      this.modelGroup = '';
      this.oldModelGroup = '';
      this.oldModelName = '';
      this.model = new ModelItemModel().models[0];
    });
  }

  delete(modal, name, group = null) {
    new Promise(resolve => {
      if (modal) {  // if modal was given, wait for result
        this.modal.open(modal).then(result => {
          resolve(result);
        });
      }
      else {
        resolve(true);
      }
    }).then(res => {
      if (res) {
        if (group) {  // delete model group if given
          this.api.delete(`/model/${group}/${name}`, () => {
            this.loadGroups();
          });
        }
        else {  // delete model file
          this.api.delete(`/model/file/${name}`, () => {
            this.d.arr.modelFiles.splice(this.d.arr.modelFiles.findIndex(e => e.name === name), 1);
          });
        }
      }
    });
  }

}
