import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect, Modal } from 'amos-framework';
import AmosWebSocket from 'amos-websocket';
import * as endConf from 'amos-processor/lib/config/endconf';
import PilotController from 'amos-viz/lib/board/PilotController';
import SysWsURL, { completeToken } from './../../consts/wsUrlConsts';
import ScreenSaverView from './screenSaver/ScreenSaverView';

// import Three3dView from './Three3dView';
import Three3dView from './View3D';
import { eventTopics } from './consts';

const eventConnect = Connect.eventConnect;
const AmosConfig = endConf.AmosConfig;
const enableScreenSaver = false;//AmosConfig.screenSaverConf.enable;
const delayTime = AmosConfig.screenSaverConf.delayTime;

@eventConnect
class View3DRoot extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showScreenSaver: false //是否打开屏保
    };
    this.pushTimeOutId = null;
  }

  componentDidMount() {}

  componentWillUnmount() {
    if (this.pushTimeOutId){
      clearTimeout(this.pushTimeOutId);
      this.pushTimeOutId = null;
    }
  }

  onLoadCompleted = () => {
    console.log('3d resources load completed');
    this.setState({
      showScreenSaver: true
    });
  };

  getScreenSaverContext = () => {
    return <ScreenSaverView />;
  };

  getScreenSaver() {
    const { showScreenSaver } = this.state;
    return enableScreenSaver && showScreenSaver && (
      <PilotController delayTime={delayTime}>
        <Modal
          className="screen-saver-view-modal"
          width="100%"
          height="100%"
          closable={false}
          noDefaultHeader
          visible
          destroyContent
          noDefaultFooter
          content={this.getScreenSaverContext()}
        />
      </PilotController>
    );
  }

  hiddenScreenSaver = () => {
    this.setState({ showScreenSaver: false });
    if (enableScreenSaver) {
      this.pushTimeOutId = setTimeout(() => {
        this.setState({
          showScreenSaver: true
        });
      }, 1000);
    }
  }

  /**
   * 监控视图消息 (view3d ws)
   */
  handleData = (data = {}) => {
    console.log('view3d ws data:', data);
    const topic = data.topic || eventTopics.base3d_view;
    this.props.trigger(topic, data);
  };

  render() {
    const wsURL = completeToken(SysWsURL.view3dws);
    return (
      <div className="sys-view-3d">
        <AmosWebSocket ref={node => this.aws = node} url={wsURL} onMessage={this.handleData} reconnect debug />
        <Three3dView onLoadCompleted={this.onLoadCompleted} hiddenScreenSaver={this.hiddenScreenSaver} />
        {this.getScreenSaver()}
      </div>
    );
  }
}

View3DRoot.propTypes = {
  subscribe: PropTypes.func,
  trigger: PropTypes.func
};

export default View3DRoot;
