import { ICellRendererComp, ICellRendererParams } from "ag-grid-community";
import { createOverrideContext, Container, ViewResources } from 'aurelia-framework';
import { ViewCompiler, View, ViewSlot } from 'aurelia-templating';

export default abstract class BaseRenderer implements ICellRendererComp {
    protected eGui: HTMLElement;

    protected view: View;
    protected viewSlot: ViewSlot;
    protected params: ICellRendererParams;

    public init(params: ICellRendererParams) {
        this.params = params;
    }

    public async setupGui() {
        this.eGui = document.createElement('div');
        this.eGui.style.width = '100%';
        this.eGui.style.height = '100%';

        let content: string = await this.setupContentGui();
        let html: string = `<template>${content}</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();
    }

    public abstract setupContentGui(): string;

    public getGui(): HTMLElement {
        return this.eGui;
    }

    public refresh(params): boolean {
        return true;
    }

    public destroy() {
        if (this.view) this.view.unbind();
        if (this.viewSlot) this.viewSlot.detached();
    }

    public getValueToDisplay() {
        return this.params.valueFormatted ? this.params.valueFormatted : this.params.value;
    }
}