import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { utils } from 'amos-tool';
import loadScripts from 'dt2react/lib/utils/loadScripts';
import VideoProcess from './VideoProcess';

const uniqueId = () => parseInt(Date.now() * Math.random()).toString(); 

export class HikvisionVideo extends Component {
  static propTypes = {
    layout: PropTypes.string,
    cameraIndexCode: PropTypes.array || PropTypes.string,
    width: PropTypes.string || PropTypes.number,
    height: PropTypes.string || PropTypes.number,
    iServicePortStart: PropTypes.number,
    iServicePortEnd: PropTypes.number,
  }

  constructor(props) {
    super(props)
    this.videoProcess = null;
    this.state = {

    }
  }

  componentWillMount() {
    this.setState({ key:  uniqueId() });
  }

  componentDidMount() {
    this.initVideo();
    const { cameraIndexCode } = this.props;
    this.setState({ cameraIndexCode });
  }

  componentWillReceiveProps(nextProps) {
    const { cameraIndexCode } = nextProps;
    this.setState({ cameraIndexCode }, this.preview);
  }
  
  preview = () => {
    if (!this.videoProcess) {
      return;
    }
    const { cameraIndexCode } = this.state;
    if (cameraIndexCode && utils.isArray(cameraIndexCode)) {
      cameraIndexCode.forEach((value, index) => {
        this.videoProcess.startPreview(value, index);
      });
    } else if (cameraIndexCode){
      this.videoProcess.startPreview(cameraIndexCode);
    }
  }

  componentWillUnmount() {
    if (this.videoProcess) {
      this.videoProcess.onunload();
    }
  }

  
  initVideo = () => {
    let script = null;

    script = {
      key: 'hikvisionscripts',
      url: `/extraa/hikvision/jsWebControl-1.0.0.min.js`
    };
    loadScripts.asyncLoadScript(script, () => {
      const params = Object.assign({}, this.props, {
        appkey: '21787783',
        secret: 'teuQK4qEMgyAtDWVmZi6',
        ip: '11.11.16.4',
        port: '443',
      });
      this.videoProcess = new VideoProcess(window.WebControl, params, this.preview);
      this.videoProcess.initPlugin(this.state.key);
    });

  }

  render() {
    return (
      <div id={this.state.key}></div>
    )
  }
}

export default HikvisionVideo
