import { AppRegistry, Platform, Dimensions } from "react-native-web";
import React, {  } from "react";
import { defineProxy } from "./global";

function injectOS() {
  global.__os = Platform.OS
}
function injectDeivce() {
  var device = (global.__device = {});
  defineProxy(device, "height", () => Dimensions.get("window").height);
  defineProxy(device, "width", () => Dimensions.get("window").width);
}

function injectDeivceonApp() {
  var hyExt = window.hyExt || {};
  var consts = hyExt.consts || {};

  window.__device = {
    width: consts.screenWidth || 0,
    height: consts.screenHeight || 0,
  };
}

if (global.__os == null) {
  injectOS()
}
if (global.__os == "web") {
  injectDeivce()
} else {
  injectDeivceonApp()
}

export const registerApp = (componentName, component) => {
  class AppRoot extends React.Component {
    removeFirstScreenByAuto() {
      if (window.__autoRemoveFirstScreen) {
        window.__removeFirstScreen && window.__removeFirstScreen()
      }
    }

    componentDidMount() {
      this.removeFirstScreenByAuto()
    }

    componentDidCatch(error, info) {
      this.removeFirstScreenByAuto()
      var err = error || new Error('AppRoot Catch Error')
      throw err
    }

    render() {
      return React.createElement(component)
    }
  }

  if (Platform.OS === "web") {
    AppRegistry.registerComponent(componentName, () => AppRoot);
    // 不兼容的特性, 升级到大版本.
    // 需要相匹配的 beyond builder.
    // AppRegistry.runApplication(componentName, {rootTag: document.getElementById('root')})
  } else {
    throw new Error("the platform is not web");
  }
};

export const SDK = window.hyExt;
export const Taf = window.Taf;
