package com.yeejoin.amos.uart.business.controller;

import com.yeejoin.amos.connect.dao.entity.UartVo;
import com.yeejoin.amos.op.core.common.response.CommonResponse;
import com.yeejoin.amos.op.core.util.CommonResponseUtil;
import com.yeejoin.amos.security.authorization.Authorization;
import com.yeejoin.amos.uart.business.param.UartParam;
import com.yeejoin.amos.uart.business.service.intfc.UartService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping(value = "/uart")
@Api(tags = "串口api")
public class UartController {

    @Autowired
    private UartService uartService;



    public CommonResponse createUart(UartVo uart) {
        return null;
    }

    public CommonResponse deleteUart(Long[] ids) {
        return null;
    }

    public CommonResponse findUartById(Long id) {
        return null;
    }

    public CommonResponse findAll() {
        return null;
    }

    public CommonResponse findSystemSerialPort() {
        return null;
    }

    @PostMapping(value = "/sendData", produces = "application/json;charset=UTF-8")
    @Authorization(ingore = true)
    public CommonResponse sendData(@RequestBody UartParam param) {
        uartService.sendData(param.getComPort(), param.getMessage());
        return CommonResponseUtil.success();
    }

    @PostMapping(value = "/sendFile", produces = "application/json;charset=UTF-8")
    @Authorization(ingore = true)
    public CommonResponse sendFile(@RequestParam(value="file", required = false) MultipartFile file, @RequestParam("serialPort") String serialPort) {
        if (ObjectUtils.isEmpty(file)) {
            return CommonResponseUtil.failure("文件不可以为空");
        }
        if (ObjectUtils.isEmpty("serialPort")) {
            return CommonResponseUtil.failure("串口不可以为空");
        }
        InputStream is = null;
        try {
            is = file.getInputStream();
            int iAvail = is.available();
            byte[] bytes = new byte[iAvail];
            is.read(bytes);
            uartService.sendBytes(serialPort, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return CommonResponseUtil.success();
    }
}
