package easydo.technology.controller;

import com.alibaba.fastjson.JSONObject;
import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.MinioFile;
import easydo.technology.service.MinioService;
import easydo.technology.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.Part;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Collection;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class MinioController {
    @Resource
    private MinioService minioService;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Value("${minio.bucket-name}")
    String BUCKET_NAME;

    @RequestMapping(value = "/upload")
    public Object uploadAihazard(MultipartHttpServletRequest request) throws Exception {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        String path;
        try {
            Collection<Part> parts = request.getParts();

            JSONObject res = new JSONObject();
            JSONObject expands = new JSONObject();
            if (parts.isEmpty()) {
                throw new BizException("it is empty");
            }
            for (Part part : parts) {
                inputStream = part.getInputStream();
                outputStream = new ByteArrayOutputStream();

                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1)
                    outputStream.write(buffer, 0, len);

                String[] items = part.getSubmittedFileName().split("\\.");
                String fileName = UUID.randomUUID().toString() + "." + items[items.length - 1];
                InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
                path = minioService.uploadFile(BUCKET_NAME, is, fileName);
                expands.put("file", path);
                res.put("code", 200);
                res.put("expands", expands);
                res.put("message", "success");
                break;
            }
            return new ResponseEntity<>(res, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != outputStream) {
                outputStream.close();
            }
            if (null != inputStream) {
                inputStream.close();
            }
        }
    }

    @RequestMapping(value = "/remove")
    public Object remove(@RequestBody MinioFile file) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            if (StringUtil.isNotEmpty(file.getPath())) {
                String buckName = file.getPath().substring(1).split("/")[0];
                String objectName = file.getPath().substring(1 + buckName.length() + 1);
                minioService.removeFile(buckName, objectName);
            }
            if (StringUtil.isNotEmpty(file.getId())) {
                jdbcClient.jdbcRemoveById(file, connection);
            }
            return new ResponseEntity<>(file, HttpStatus.OK);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }
}
