package net.educoder.ecsonar.task;

import net.educoder.ecsonar.model.api.SonarRequest;
import net.educoder.ecsonar.services.SonarService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: youys
 * @Date: 2022/1/12
 * @Description:
 */
public class ReadExcelRunnable implements Runnable{

    private final Logger log = LoggerFactory.getLogger(getClass());

    private SonarRequest sonarRequest;
    private SonarService sonarService;

    public ReadExcelRunnable(SonarRequest sonarRequest,SonarService sonarService){
        this.sonarRequest = sonarRequest;
        this.sonarService = sonarService;
    }


    @Override
    public void run() {

        String uid = sonarRequest.getPersonList().get(0).getUid();
        int homeworkId = sonarRequest.getHomeworkId();
        String path = String.format("/tmp/%d/%s/", homeworkId, uid);
        File file = new File(path);
        if(!file.exists()){
            file.mkdir();
        }
//        for (Person person : sonarRequest.getPersonList()) {
//            String[] split = StringUtils.split(person.getDownloadUrl(), "/");
//            String zipFilename = UrlUtil.getURLDecoderString(split[split.length - 1]);
//            try {
//                download(person.getDownloadUrl(),path+zipFilename);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        String key = String.format("%d-%s", homeworkId, uid);
        log.info("开始调用sonar:{}",key);
        sonarService.sonar(path,key);
    }

    private void download(String zipUrl, String zipPath) throws IOException {
        log.info("下载文件: {}-{}", zipUrl, zipPath);

        String cookie = "_educoder_session=1f4bf34409fec2180b99aa1cbf0b7586";
        URL url = new URL(zipUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Cookie", cookie);
        conn.setDoInput(true);

        String fileName = conn.getHeaderField("Content-Disposition");
        if(StringUtils.isNotEmpty(fileName)){
            fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
            fileName = fileName.substring(fileName.indexOf("filename=")+10,fileName.length()-1);
            zipPath = zipPath.substring(0, zipPath.lastIndexOf("/")+1) + fileName;
        }
        try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
             FileOutputStream fileOutputStream = new FileOutputStream(zipPath)) {
            byte dataBuffer[] = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        } catch (IOException e) {
            log.error("文件下载失败: {}-{}", zipUrl, zipPath);
            throw e;
        }

    }
}
