import * as React from 'react';

export type HtmlType = string | React.ReactElement;

export interface PreviewProps {
  html: HtmlType;
  className?: string;
}

export abstract class Preview<T extends HTMLElement> extends React.Component<PreviewProps, any> {
  protected el: any;
  constructor(props: any) {
    super(props);
    this.el = null;
  }
  abstract getHtml(): string;
  getHeight() {
    return this.el ? this.el.offsetHeight : 0;
  }
}

export class HtmlRender extends Preview<HTMLDivElement> {
  getHtml() {
    if (typeof this.props.html === 'string') {
      return this.props.html;
    }
    if (this.el) {
      return this.el.innerHTML;
    } else {
      return '';
    }
  }
  render() {
    return typeof this.props.html === 'string'
      ? React.createElement('div', {
          ref: el=>this.el=el,
          dangerouslySetInnerHTML: { __html: this.props.html },
          className: this.props.className || 'custom-html-style',
        })
      : React.createElement(
          'div',
          {
            ref: el=>this.el=el,
            className: this.props.className || 'custom-html-style',
          },
          this.props.html,
        );
  }
}

export default HtmlRender;
