package org.jeecg.modules.word;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.config.JeecgBaseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.security.Signer;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

@RestController
@RequestMapping("word")
public class WordController {


    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JeecgBaseConfig jeecgBaseConfig;


    @PostMapping("/save")
    @ResponseBody
    public void save(HttpServletRequest request, HttpServletResponse response) throws IOException {


        PrintWriter writer = response.getWriter();

        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";

        Map<String, Object> map = objectMapper.readValue(body, objectMapper.getTypeFactory().constructMapType(HashMap.class, String.class, Object.class));


        System.out.println(map);
        if ((Integer) map.get("status") == 2) {
            String downloadUri = (String) map.get("url");


            String key = map.get("key").toString();

            String fileName =  key.split("=")[0] + "." + map.get("filetype");

            URL url = new URL(downloadUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();
            String pathForSave = jeecgBaseConfig.getPath().getUpload() + File.separator + key.split("=")[1] + File.separator + fileName;

            File savedFile = new File(pathForSave);
            try (FileOutputStream out = new FileOutputStream(savedFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
            }

            connection.disconnect();
        }
        writer.write("{\"error\":0}");
    }



}


