import { createElement, Component, findDOMNode } from 'rax';
import { Env } from 'weex-nuke';

const { isWeex } = Env;
let canvasWeex = null;

if (isWeex) {
  canvasWeex = require('./canvas-weex');
}

class Canvas extends Component {
  constructor() {
    super();
    this.getContext = this.getContext.bind(this);
  }
  getContext() {
    const canvas = findDOMNode(this.refs.canvas);

    if (isWeex) {
      return new Promise((resolve) => {
        requestAnimationFrame(() => {
          resolve(canvasWeex.init(canvas));
        });
      });
    }
    return new Promise((resolve) => {
      if (canvas && canvas.getContext) {
        const context = canvas.getContext('2d');
        context.render = () => { };
        resolve(context);
      }
    });
  }


  render() {
    const { style = {} } = this.props;

    if (isWeex) {
      return <gcanvas {...this.props} ref="canvas" />;
    }
    return <canvas {...this.props} width={style.width} height={style.height} ref="canvas" />;
  }
}

export default Canvas;
