import { dispatch, getState } from './utils';
import { routerRedux } from 'dva';
import config from '@/config';

const isApp = () => {
  const r = typeof window.plus !== 'undefined';
  // console.log(r);
  return r;
};

const barcodeId = 'barcode'
const scan = () => {
  if (!isApp()) return Promise.resolve('');
  return new Promise<string>(resolve => {
    const { barcode, webview } = window.plus;
    const bc = barcode.create(barcodeId, [barcode.QR], {
      position: 'absolute',
      left: '0px',
      top: '100px',
      width: '100%',
      height: '500px',
    });
    bc.onmarked = (_, code) => {
      resolve(code);
      bc.close();
    };
    bc.onerror = () => {
      resolve('');
      bc.close();
    }
    webview.currentWebview().append(bc);
    bc.start();
  });
};

const backButtonHandler = () => {
  const barcode = window.plus.barcode.getBarcodeById(barcodeId);
  if (barcode) {
    barcode.close();
    return;
  }
  const { pathname } = getState().router.location;
  if (config.exitPaths.includes(pathname)) {
    window.plus.runtime.quit();
  } else {
    dispatch(routerRedux.goBack());
  }
};
const init = () => {
  if (!isApp()) return;
  window.plus.key.addEventListener('backbutton', backButtonHandler);
};

const destory = () => {
  if (!isApp()) return;
  window.plus.key.removeEventListener('backbutton', backButtonHandler);
};

const share = (content: string) => {
  if (!isApp()) return;
  window.plus.share.sendWithSystem({
    type: 'text',
    content,
  }, () => { });
};

const restart = () => {
  if (!isApp()) return;
  window.plus.runtime.restart();
}

export {
  init,
  isApp,
  scan,
  share,
  destory,
  restart,
};

export default {
  init,
  isApp,
  scan,
  share,
  destory,
  restart,
};
