package tech.glinfo.enbao.modules.mqtt.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.glinfo.enbao.common.annotation.Login;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.config.MqttGateway;
import tech.glinfo.enbao.modules.mqtt.entity.AuthEntity;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("mqtt")
public class MqttController {

    @Resource
    private MqttGateway mqttGateway;

    @PostMapping("auth")
    public ResponseEntity<Object> auth(@RequestBody AuthEntity auth){
        log.info("请求参数：{}", auth);
        String pwd = EncryptUtil.encrypt(auth.getUsername());
        if(auth.getPassword() != null && auth.getPassword().equals(pwd)) {
            boolean isSuperuser = false;
            if(auth.getUsername().startsWith("168EG")) {//暂时写死
                isSuperuser = true;
            }
            MapUtils rtn = new MapUtils().put("result", "allow").put("is_superuser", isSuperuser);
            return new ResponseEntity<Object>(rtn, HttpStatus.OK);
        } else {
            return new ResponseEntity<Object>("auth deny!", HttpStatus.UNAUTHORIZED);
        }
    }

    @Login
    @PostMapping("send")
    public R sendToMqtt(@RequestBody Map<String, String> params) {
        String  data = params.get("data");
        String  topic = params.get("topic");
        if(!StringUtils.isBlank(data, topic)) {
            log.info("\nsend message >>>> topic : {}, data : {}", topic, data);
            byte[] datas = ByteUtils.hexStrToBinaryStr(data);
            mqttGateway.sendToMqtt(datas, topic);
        }
        return R.ok();
    }
}
