import { Component, Input, OnChanges }  from '@angular/core';
import { HelperService }                from '../../../../services/svc.helper'
@Component({
    moduleId: module.id+ '',
    selector: 'attributes',
    templateUrl: './tpl.attributes.pug',
    styleUrls: ['sty.attributes.scss']
})

export class AttributesComponent implements OnChanges {

    @Input('attributes') attributes: any = [];
    @Input('sku') sku: string;

    measurementType: string;
    measurements: any = [];

    dimensions = ['width', 'height', 'length', 'depth', 'seat_height', 'cube', 'carton_weight', 'height_under_table', 'weight'];
    dimensionsToDisplay: any = [];

    descriptions = ['quantity_in_carton', 'type', 'assembly', 'material', 'notes'];
    descriptionsToDisplay: any = [];

    constructor(
        private _helper: HelperService
    ) {}

    ngOnChanges(): void {

        this.dimensionsToDisplay = [];
        this.descriptionsToDisplay = [];

        this.measurementType = this._helper.measurementType;
        this.setMeasurementType();
        this.findAttributes();

    }

    setMeasurementType(): void {
        // Check if type is Imperial or not, TODO: Serve from service
        if(this.measurementType == 'imperial')
            this.measurements = ['inches', 'ft3', 'lb'];
        else
            this.measurements = ['cm', 'm3', 'kg'];
    }

    findAttributes(): void {

        // Put SKU into display array
        let skuAttribute = {"code": "sku", "label": "SKU", "value": this.sku}
        this.descriptionsToDisplay.push(skuAttribute);

        for(let attribute of this.attributes) {


            // Run over attribute to check if theres a measurement type on the code
             let attributeMeasurementType = this.identify(attribute.code, '_');

             // Check if the attribute is in description or dimensions array, if in any - push to display array
            if( this.descriptions.indexOf( attribute.code ) >= 0 ) {
                this.descriptionsToDisplay.push(attribute);
            } else if( this.dimensions.indexOf(attributeMeasurementType.identifier)  >= 0 && this.measurements.indexOf( attributeMeasurementType.element ) >= 0 && attribute.value > 0) {
                this.dimensionsToDisplay.push(attribute);
            }
        }
    }

    identify(string: string, delimiter: string) {
        if(typeof delimiter === "undefined")
            delimiter = "_";
   
        var split = string.split(delimiter);
        var end = split.pop();

        return {
            "identifier": split.join(delimiter),
            "element": end
        };
    }
}