import precompile from '../../precompile';

import { html, render as litHtmlRender } from 'lit-html';
import { repeat } from 'lit-html/directives/repeat.js';
import createFilters from '../../../smi-core/src/core/filters/create-filters';

/**
 * Turn a Liquid template string into an executable render function
 * @param template - Liquid template string
 * @returns (state: object) => HTMLElement
 */
export async function getRenderFn(template: string, { script } = { script: '' }) {
  const container = document.createElement('div');
  document.body.appendChild(container);

  const compiled = await precompile([
    {
      name: 'views/main.liquid',
      content: template
    },
    {
      name: 'styles/main.less',
      content: ''
    },
    {
      name: 'scripts/script.js',
      content: script
    },
    {
      name: 'locales/en-US.json',
      content: '{}'
    }
  ]);

  // precompile returns a "function template() { }" string
  // we use eval to convert it to an executable function
  const templateGenerator = eval('(' + compiled + ')');

  const filters = createFilters('en-US');

  return (state: object) => {
    const localeRenderFunctions = templateGenerator(html, repeat);
    const renderResult = localeRenderFunctions['en-US'](state, filters);
    litHtmlRender(renderResult, container);
    return container;
  };
}
