import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withSubscribeMQTT as withSubscribeMQTT2, parseMessage } from 'amos-mqtt';

/**
 * 公共消息处理，主要添加接收到消息的标志，易于组件进行判断
 * @param {*} topic
 * @returns
 */
export default function withSubscribeMQTT({ topic, dispatch, judge }){
  return function(WrappedComponent){

    @withSubscribeMQTT2({
      topic,
      dispatch: dispatch ?  dispatch : function(_topic, message, packet){
        const newMsg = parseMessage(message);
        if (judge ? judge(_topic) : _topic === topic) {
          // console.log('接收到消息======>', newMsg, _topic);
          this.setState({ data: { message: newMsg, messageFlag: Date.now() } });
        }
      }
    })
    class WrapperComponent extends Component {
      constructor(props) {
        super(props);
      }

      render() {
        const { message, messageFlag, children } = this.props.data || {};
        if (messageFlag) {
          return (
            <WrappedComponent {...this.props} data={message} messageFlag={messageFlag}>
              {children}
            </WrappedComponent>
          );
        } else {
          return (
            <WrappedComponent {...this.props} data={this.props.data}>
              {children}
            </WrappedComponent>
          );
        }
      }
    }

    WrapperComponent.propTypes = {
      children: PropTypes.any,
      data: PropTypes.any
    };
    return WrapperComponent;
  };
}
