import { Component, Input, Output, OnChanges, EventEmitter, ChangeDetectionStrategy } from '@angular/core';

import { HelperService }                                                              from '../../../../services/svc.helper'

@Component({
    moduleId: module.id+'',
    selector: 'configurables',
    templateUrl: './tpl.configurables.pug',
    styleUrls: ['./sty.configurables.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class ConfigurablesComponent implements OnChanges {

    showChildren: boolean = true;
    currentChild: any;

    currentlySelectedElement: any;

    @Input('product') product: any;
    @Input('init') base: any;
    @Output() output = new EventEmitter<any>();

    constructor(
        private _helper: HelperService
    ) {}

    server: string = this._helper.server

    ngOnChanges(): void {

        this.product.values.sort((a,b) => {
            if(a.family < b.family) return -1
            if(a.family > b.family) return 1
            return 0
        })

        for(let values of this.product.values) {
            values.values.sort((a,b) => {
                if(a.name < b.name) return -1
                if(a.name > b.name) return 1
                return 0
            })
        }

        if(this.product.values.length == 1) {

            if(this.product.type == 'Frame') {
                if(this.product.values[0].values.length > 1) {

                    this.currentChild = this.product.values[0].values
                }
            } else {
                this.currentChild = this.product.values[0].values;
            }
        }


        this.currentlySelectedElement = this.base[this.product.type];
        
    }


    // TODO: Move to shared or global
    capitalize(string) {

        let collection = string.split(' ');
        let cleanedString: string = '';

        // Iterate over the split string
        for(let group of collection) {
            // Make sure the string has content
            if(group.length > 0) {

                // ucfirst
                group = group.toLowerCase()
                group = group.charAt(0).toUpperCase() + group.slice(1)

                // Add with _ as seperator if space
                if(cleanedString) {
                    cleanedString = cleanedString + '_' + group 
                } else {
                    cleanedString = group
                }
            }   
        }

        return cleanedString
    }

    populateChild(value: any) {
        this.currentChild = value;
    }
    
    populateOutput(name: string, suffix: string) {

        this.currentlySelectedElement = suffix;
        this.output.emit( { "name": name, "suffix": suffix } );
    }
}



