/** @jsx createElement */

'use strict';

import {
  Component,
  createElement,
  PropTypes,
  unmountComponentAtNode,
  findDOMNode,
  render,
} from 'rax';
import dom from 'nuke-dom';
import Env from 'nuke-env';

const { isWeex } = Env;
import Picker from './picker';

const noop = () => {};

let pickerInstance = null;


let container = null;

export function show(options = {}, onSelect, onCancel, onShow, onFail) {
  onSelect = onSelect || noop;
  onShow = onShow || noop;
  onFail = onFail || noop;
  onCancel = onCancel || noop;

  const {
    title,
    dataSource,
    selectedKey,
    locale,
    maskClosable = true,
    visible,
    value,
    content,
    children,
    ...others
  } = options;
  if (!dataSource || !dataSource[0]) {
    onFail({ err: 'empty dataSource' });
    return;
  }
  const attrs = {
    title,
    maskClosable,
    dataSource,
    selectedKey: value || selectedKey,
    afterClose: afterCloseCallback,
    onCancel,
    onDone: onSelect,
  };
  if (locale) {
    attrs.locale = locale;
  }
  let picker = <Picker {...others} {...attrs} />;

  function afterCloseCallback() {
    unmountComponentAtNode(container);
    document.body.removeChild(container);

    pickerInstance = picker = container = null;
  }
  //   function onSelectCallback(res) {
  //     let result = { success: true };
  //     if (res instanceof Array && res.length > 0) {
  //       result.data = res[0]

  //     }
  //     onSelect(result);
  //   }
  function afterOpenCallback(d) {
    afterOpen(d);
  }
  if (options.container) {
    container = findDOMNode(options.container);
  }
  // container = options.container || null;
  if (!container) {
    container = dom.createEle('div', { t: 'id', abc: '_nuke_wrap' });
    document.body.appendChild(container);
  }
  render(picker, container, function () {
    pickerInstance = this;
    pickerInstance.wrappedInstance.show();
  });
}

export function hide() {
  if (isWeex) {
    // native 暂不支持
  } else if (pickerInstance) {
    pickerInstance.wrappedInstance.hide();
  }
}
