import { Pipe, PipeTransform, Input}                            from '@angular/core'
import { SharedService }                                        from '../services/svc.shared'
@Pipe({
    name: "translate"
})

export class TranslatePipe {

    @Input() trnsl: string;
    observable: any;

    subscriptions: any;

    constructor(
        private _shared: SharedService
    ) {}

    /**
     * Extended translation pipe
     * 
     * Translation tool to automatically populate the WP translator, define areas and descriptions
     * This allows for the `editor` to see what the translation is actually placed
     * 
     * This also allows us to specify where a specific translation is used, so we can reuse it.
     * `Area` and `Description` are not mandatory for the technology to work.
     * 
     * see the `@tutorial` for usage
     * 
     * @tutorial {{ 'string' | translate:'area?':'description?' }}
     * @param {string} key > identifier for the translatable value 
     * @param {string} area > Defined area where the translation should work  
     * @param {string} description > a description of what this specific translate does, if needed
     */
    transform(key: string, area?: string, description?: string): any {

        // Area will always be lowercase 
        area = (!!area) ? area.toLowerCase() : 'default'


        this.observable = this._shared.getTranslates()

        if(!!this.observable) {
            if (this.observable && !!this.observable[area] && !!this.observable[area][key]) {
    
    
                // if translation exists; none of them (0, null, undefinded)
    
                // console.log("Both defined : " + this.observable[area][key]);
                return this.observable[area][key];
    
            } else if (typeof this.observable[area] == 'undefined') {
                // Either area or key does not exists
    
                // console.log("Area does not exist or not defined")
                this.setTranslates(key, area, description)
                return key;
    
            } else if (typeof this.observable[area][key] == 'undefined') {
                // Either area or key does not exists
    
                // console.log("Key does not exists or not defined")
                this.setTranslates(key, area, description)
                return key;
    
            } else {
                // both defined but value is empty
    
                let translation = (this.observable[area][key] != '') ? this.observable[area][key] : key;
                // console.log("Defined but translation is empty : " + translation + " -> " + this.observable[area][key]);
                return translation;
    
            } 
        }
    }

    private setTranslates(key: string, area?: string, description?: string) : void {

        this._shared.setTranslates(key, area, description);

    }
}
