import { ServiceBase } from './../../../../data/service-base';
import { Container, BindingEngine, inject, Disposable } from 'aurelia-framework';
import { ICellEditorComp, ICellEditorParams } from "ag-grid-community";
import { ViewCompiler, ViewResources, ViewSlot, View } from 'aurelia-templating';
import { createOverrideContext } from 'aurelia-binding';

export default class Select2CellEditor implements ICellEditorComp {
    eGui: HTMLElement;
    view: View;
    viewSlot: ViewSlot;
    dataService: ServiceBase<any>;
    entity;
    valuePropertyName: string;
    displayPropertyName: any;
    params: ICellEditorParams;
    disposable: Disposable;
    bindingEngine: BindingEngine;
    /**
     *
     */
    constructor() {            
        this.bindingEngine = Container.instance.get(BindingEngine);
    }
    getValue() {
        return this.entity[this.valuePropertyName];
        //return this.entity[this.displayPropertyName] != null ? this.entity[this.displayPropertyName] .denomination._translation : null;
    }

    getGui(): HTMLElement {
        this.setupGui();
        return this.eGui;
    }
    isPopup?(): boolean {
        return false;
    }
    afterGuiAttached() {
        $(this.eGui).find('select').select2('open');
    }
    destroy() {        
        this.view.detached();
        this.viewSlot.detached();      
        this.disposable.dispose();  
    }


    init?(params: import("ag-grid-community").ICellEditorParams | any ) {  
        this.params = params;
        this.dataService = params.dataService;
        this.entity = params.data;
        this.valuePropertyName = params.valuePropertyName;
        this.displayPropertyName = params.displayPropertyName;

        var observer = this.bindingEngine.propertyObserver(this.entity, this.valuePropertyName);
        this.disposable = observer.subscribe((n, o) => this.propertyChanged(n, o));
    }    
    public entityMatcher = (a, b) => {
        var a_id = a != null && a.id != null ? a.id : a;
        var b_id = b != null && b.id != null ? b.id : b;
        if (a_id == "") a_id = 0;
        if (b_id == "") b_id = 0;
        return (a_id != null && b_id != null && a_id.toString != null && b_id.toString != null) ? a_id.toString() === b_id.toString() : a_id == b_id;
    };
    propertyChanged(newValue: number, oldValue: number){
        console.log(`PropertyChanged NewValue = ${newValue} ; OldValue= ${oldValue}`);
        if (newValue != oldValue) {
            this.params.stopEditing();
        }
    }

    setupGui() {
        this.eGui = document.createElement('div');
        this.eGui.style.width = '100%';
        this.eGui.style.height = '100%';
    
        let display = "${entity." + this.displayPropertyName + ".denomination._translation}";
        var html = `
        <template>
            <select matcher.bind="entityMatcher" value.bind="entity.${this.valuePropertyName} & validate"
                t="[data-placeholder]general.chooseAnOption" 
                data-allow-clear="true"
                select2="value.bind: entity.${this.valuePropertyName};                
                    data-source.bind: dataService.gridDataSource;
                    options-text: denomination._translation;
                    options-value: id">
                <option></option> 
                <option value.bind="entity.${this.valuePropertyName}">${display}</option>           
            </select>
        </template>`;
    
        let viewCompiler = Container.instance.get(ViewCompiler);
        let viewResources = Container.instance.get(ViewResources);
        let viewFactory = viewCompiler.compile(html, viewResources);
        this.view = viewFactory.create(Container.instance);
        this.viewSlot = new ViewSlot(this.eGui, true);    
        this.viewSlot.add(this.view);
        this.view.bind(this, createOverrideContext(this));
        this.viewSlot.attached();
      }

}