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


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

  materials: MaterialModel[] = [];                    // all materials
  templateKeys: {key: string, label: string}[] = [];  // material template keys
  materialStatus = {validated: true, new: true, deleted: false};  // material statuses to show
  materialSearch = '';   // material name search string
  sampleSelect = false;  // set to true to show checkboxes for validation

  page = 1;  // page settings
  pages = 0;
  pageSize = 25;

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

  ngOnInit(): void {
    this.loadMaterials();
    this.d.load('materialTemplates', () => {
      this.d.arr.materialTemplates.forEach(template => {
        template.parameters.forEach(parameter => {
          this.templateKeys.push({key: parameter.name, label: `${this.ucFirst(template.name)} ${parameter.name}`});
        });
      });
      // filter out duplicates
      this.templateKeys = this.templateKeys.filter((e, i, a) => !a.slice(0, i).find(el => el.key === e.key));
    });
  }

  loadMaterials() {
    this.api.get<MaterialModel[]>('/materials?' +
      Object.entries(this.materialStatus).filter(e => e[1]).map(e => 'status[]=' + e[0]).join('&'), data => {
      this.materials = data.map(e => new MaterialModel().deserialize(e));
      this.pages = Math.ceil(this.materials.length / this.pageSize);
      this.page = 1;
    });
  }

  validate() {
    if (this.sampleSelect) {  // selection was done do actual validation
      this.materials.forEach(sample => {
        if (sample.selected) {
          this.api.put('/material/validate/' + sample._id);
        }
      });
      this.loadMaterials();
      this.sampleSelect = false;
    }
    else {  // activate validation mode
      this.sampleSelect = true;
    }
  }

  selectAll(event) {  // toggle selection for all items except deleted ones
    this.materials.forEach(material => {
      if (material.status !== 'deleted') {
        material.selected = event.target.checked;
      }
      else {
        material.selected = false;
      }
    });
  }

  restoreMaterial(id, modal) {
    this.modal.open(modal).then(res => {
      if (res) {
        this.api.put('/sample/restore/' + id, {}, ignore => {
          this.materials.find(e => e._id === id).status = 'new';
        });
      }
    });
  }

  ucFirst(string) {  // convert first character of string to uppercase
    return string[0].toUpperCase() + string.slice(1);
  }

  materialFilter(ms) {  // filter function for material names
    return e => e.name.indexOf(ms) >= 0;
  }

}
