import { Result, AppError, success } from '../utils/result';
import { WidgetDataLoaderInterface } from './widget-data-loader-interface';
import { WidgetInterface } from './widget-interface';
import Handlebars from 'handlebars';

export class TextWidget implements WidgetInterface<any, any, any, any, any> {
  constructor(
    public dataLoader: WidgetDataLoaderInterface<any, any, any>,
    public type: string,
    public template: string,
  ) {}

  async render(
    widgetParams: any,
    dataLoaderParams: any,
    dashboardParams: any,
  ): Promise<Result<any, AppError>> {
    const params = {
      widgetParams,
      dataLoaderParams,
      dashboardParams,
    };
    const template = Handlebars.compile(this.template);
    const res = template(params);
    return success(res);
  }
}

export function createTextWidget(
  dataLoader: WidgetDataLoaderInterface<any, any, any>,
  type: string,
  template: string,
): WidgetInterface<any, any, any, any, any> {
  return new TextWidget(dataLoader, type, template);
}
