import { ProductService } from '@nodeart/productservice';
import { DbAbstractionLayer } from '@nodeart/dal/index';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Component, OnInit } from '@angular/core';

/**
 * Component that represent a form to add new properties
 */
@Component({
  selector: 'app-add-props',
  templateUrl: './add-props.component.html',
  styleUrls: ['./add-props.component.scss']
})
export class AddPropsComponent implements OnInit {

  /**
   * Properties available to add
   */
  propOptions = ['', 'category', 'attribute', 'tag'];
  
  /**
   * New category form
   */
  categoryForm: FormGroup;

  /**
   * New attribute form
   */
  attributeForm: FormGroup;

  /**
   * New tag form
   */
  tagForm: FormGroup;

  /**
   * Selected property to add
   */
  selectValue = "";

  categories = [];
  addedChilds = [];
  category = "";
  constructor(private fb: FormBuilder, private dal: DbAbstractionLayer, private productService: ProductService) {
    this.categoryForm = fb.group({
      name: '',
      tags: [],
      attrs: []
    });
    this.attributeForm = fb.group({
      name: '',
      desc: '',
      childs: []
    });
    this.tagForm = fb.group({
      name: '',
      desc: ''
    });
   }


  ngOnInit() {
    this.getCategories();
  }

  addCategory(){
    this.categoryForm.patchValue({
      tags: ['1234', '1234'],
      attrs: ['1234', '1234']
    });
    this.dal.addCategory(this.categoryForm);
  }
  
  change(){
    this.categoryForm.patchValue({
      name: '',
      tags: [],
      attrs: []
    });
    this.attributeForm.patchValue({
      name: '',
      desc: '',
      childs: []
    });
  }

  addAttribute(categoryId){
    this.attributeForm.patchValue({
      childs: this.addedChilds
    });
    this.dal.addAttribute(this.attributeForm, categoryId);
  }

  addTag(categoryId){
    this.dal.addTag(this.tagForm, categoryId);
  }


  getCategories(){
    this.productService.getCategories().on('value', data => {
      if(data.val()) {
        this.categories = data.val().map(item => {
              item['_source']['id'] = item['_id'];
              return item['_source'];
        });
      }
    });
  }

  addChild(){
    this.addedChilds.push({
      key: '',
      name: ''
    });
  }

  removeChild(index){
    this.addedChilds.splice(index, 1);
  }
}
