package com.bonus.common.houqin.mq.rabbit.mqtt;

import com.bonus.common.houqin.mq.mqtt.MqttAuth;
import com.bonus.common.houqin.mq.mqtt.MqttAuthCheck;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping
public class MqttAuthController {
   private final MqttAuthCheck mqttAuthCheck;

   public MqttAuthController(MqttAuthCheck mqttAuthCheck) {
      this.mqttAuthCheck = mqttAuthCheck;
   }

   @RequestMapping({"${spring.mqtt.rabbitmq.authc-url:/rabbitmq/auth/user}"})
   public void authenticating(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) throws IOException {
      MqttAuth.Authenticating.Request request = new MqttAuth.Authenticating.Request();
      request.setUsername(username);
      request.setPassword(password);
      IOUtils.write(this.mqttAuthCheck.authc(request).getResult(), response.getOutputStream(), StandardCharsets.UTF_8);
   }

   @RequestMapping({"${spring.mqtt.rabbitmq.authz-topic-url:/rabbitmq/auth/topic}"})
   public void authorizing(TopicCheck check, HttpServletResponse response) throws IOException {
      MqttAuth.Authorizing.Request request = new MqttAuth.Authorizing.Request();
      request.setTopic(check.getRouting_key().replace(".", "/"));
      request.setUsername(check.getUsername());
      IOUtils.write(this.mqttAuthCheck.authz(request).getResult(), response.getOutputStream(), StandardCharsets.UTF_8);
   }

   @RequestMapping({"${spring.mqtt.rabbitmq.authz-vhost-url:/rabbitmq/auth/vhost}"})
   public void vhost(VirtualHostCheck check, HttpServletResponse response) throws IOException {
      IOUtils.write("allow", response.getOutputStream(), StandardCharsets.UTF_8);
   }

   @RequestMapping({"${spring.mqtt.rabbitmq.authz-resource-url:/rabbitmq/auth/resource}"})
   public void resource(ResourceCheck check, HttpServletResponse response) throws IOException {
      IOUtils.write("allow", response.getOutputStream(), StandardCharsets.UTF_8);
   }
}
