import Twig from 'twig';
import * as Ace from 'brace'
import {Mode as AceTwig} from 'brace/mode/twig'
import * as Theme from 'brace/theme/solarized_light'
import * as OptionsTemplate from '../UI/template_flags.tmpl'

var test_data = {};

var options_container = null;

var base_template = null;

var base_data = {
    date: "29-05-2020 14:00",
    application: "Notification"
};

var renderCallback = null;

function processChange(event) {
    var key;
    var value;

    key = event.target.name;
    if(event.target.nodeName === "INPUT" && event.target.type.toLowerCase() === "radio")
        value = event.target.value === "1";
    else
        value = event.target.value;

    if(key != null)
    {
        var obj = {};
        obj[key] = value;
        setTestData(obj);
    }
}

function renderOptions(element, options_list)
{
    var booleanFlags = {};
    for (var key in options_list) {
        if( typeof options_list[key] === "boolean")
            booleanFlags[key] = options_list[key];
    }

    var html = OptionsTemplate({
        id: 'options-list',
        flags: booleanFlags
    });

    element.html(html);
    $('#options-list').on('change', processChange);
}

function updateOptions(element, options_list)
{
    for (var key in options_list) {
        if( typeof options_list[key] === "boolean")
        {
            if(options_list[key])
                $('#' + key + '-true-input').prop('checked', true);
            else
                $('#' + key + '-false-input').prop('checked', true);
        } else
        {
            var selector = $('#' + key + '-input');
            var val = options_list[key].toString();
            if(selector.val() !== val)
                selector.val(val);
        }
    }
}

export function render(template_source, data) {
    try {
        const context = data !== undefined ? data : test_data;

        const template = Twig.twig({
            data: template_source,
            rethrow: true
        });

        return template.render(context);
    } catch (e) {
        return "";
    }
}

function renderWithBase(subject, body)
{
    try {
        var body_template = Twig.twig({ data: body, rethrow: true});
        var subject_template = Twig.twig({ data: subject, rethrow: true});

        var body_html = body_template.render(test_data);
        var subject_html = subject_template.render(test_data);
        return base_template.render(Object.assign(base_data, {
            body_html: body_html,
            subject: subject_html
        }));
    }catch(e) {
    }
}

export function addFunction(name, fn) {
    Twig.extendFunction(name, fn);
}

export function setTestData(test_data_in) {
    test_data = Object.assign(test_data, test_data_in);

    if (renderCallback != null)
        renderCallback();
}

export function setBaseData(base_data_in) {
    base_data = Object.assign(base_data, base_data_in);
    if (renderCallback != null)
        renderCallback();
}

export function beginListening(templateSourceElem, templateShowElem) {

    function renderTemplate() {
        var val = templateSourceElem.getValue();
        var rendered_content = render(val);
        if(rendered_content)
            templateShowElem.html(rendered_content);
    }

    setTemplateDisplay(templateShowElem, [templateSourceElem], renderTemplate);
}

export function beginListeningWithBase(subjectSourceElem, bodySourceElem, templateShowElem, optionsElem) {
    options_container = optionsElem;

    function renderTemplate() {
        var body = bodySourceElem.getValue();
        var subject = subjectSourceElem.getValue();
        var rendered_content = renderWithBase(subject, body);
        if(rendered_content)
            templateShowElem.html(rendered_content);

        if(test_data != null && options_container != null)
            updateOptions(options_container, test_data);
    }

    if(test_data != null && options_container != null)
        renderOptions(options_container, test_data);

    setTemplateDisplay(templateShowElem, [bodySourceElem, subjectSourceElem], renderTemplate);
}

function setTemplateDisplay(templateShowElem, listenElems, callback)
{
    $.each(listenElems, function(index, elem){
        elem.off('change');
        elem.on('change', callback);
    });
    templateShowElem.off('click');
    templateShowElem.on('click', function(e){
        e.preventDefault();
    });

    renderCallback = callback;

    renderCallback();
}

export function initialiseEditor( form_id, name, editor_id ) {
    var element_selector = $("#" + form_id + " input[name='" + name + "']");
    var html_editor = Ace.edit(editor_id);
    html_editor.$blockScrolling = Infinity;
    html_editor.getSession().setMode('ace/mode/twig');
    html_editor.setTheme('ace/theme/solarized_light');
    html_editor.setValue(element_selector.val());
    html_editor.clearSelection();


    $("#" + form_id).on('click', function () {
        element_selector.val(html_editor.getValue());
    });

    return html_editor;
}

export function setBaseTemplate(id)
{
    base_template = Twig.twig({
        data: $('#' + id).html()
    });
}
