package cd.casic.server;

import cd.casic.ci.process.dto.req.sast.SastApplicationCreateReq;
import cd.casic.ci.process.dto.req.sast.SastIdentifiedLanguageTaskReq;
import cd.casic.ci.process.dto.req.sast.SastReportCreateReq;
import cd.casic.ci.process.dto.resp.sast.*;
import cd.casic.ci.process.engine.constant.SastConstant;
import cd.casic.ci.process.process.converter.SastConverter;
import cd.casic.ci.process.process.service.sast.SastService;
import cd.casic.ci.process.properties.SastProperties;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.redis.core.RedisTemplateUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ActiveProfiles;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

@SpringBootTest(classes = {OpsServerApplication.class})
@ActiveProfiles("local")
@Slf4j
public class SastTest {
    @Resource
    SastProperties sastProperties;
    @Resource
    SastService sastService;
    @Resource
    ThreadPoolTaskExecutor workerExecutor;
    @Resource
    RedisTemplateUtils redisTemplateUtils;
    @Resource
    private SastConverter converter;
    @Test
    public void properties(){
        System.out.println(JSON.toJSONString(sastProperties));
    }
    @Test
    public void getToken(){
        String token = sastService.getToken();
        System.out.println(token);
    }
    @Test
    public void getTokenThread(){

        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
        String token1 = "";
        String token2 = "";
        redisTemplateUtils.del("REDIS_SAST_TOKEN_KEY");
        workerExecutor.submit(()->{
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
            log.info(sastService.getToken());
        });
        workerExecutor.submit(()->{
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
            log.info(sastService.getToken());
        });
    }
    @Test
    public void applicationExist(){
        Boolean b = sastService.applicationExist("测试");
        System.out.println(b);
    }
    @Test
    public void fileUpload(){
        File file = new File("C:\\Users\\admin\\Desktop\\新建文件夹\\Java.zip");
        sastService.uploadFile(file);
    }

    @Test
    public void createIdentify(){
        SastIdentifiedLanguageTaskReq req = new SastIdentifiedLanguageTaskReq();
        List<String> fileIds = new ArrayList<>();

        fileIds.add("ed49de43-e2e9-402e-ab10-c6f00d434f43");
        req.setFileIds(fileIds);
        SastIdentifiedLanguageTaskResp resp = sastService.createIdentifiedLanguageTask(req);
        System.out.println(resp);
    }

    @Test
    public void getIdentify(){
        SastIdentifiedLanguageTaskResp resp = sastService.getIdentifiedLanguageTaskStatus("2c18c2f4-2c31-41d7-8199-e08bb7b36378");
        System.out.println(JSON.toJSONString(resp));
    }
    @Test
    public void getEngineConfig(){
        List<String> languageIdList= new ArrayList<>();
        languageIdList.add("17417899-2c50-11ee-a171-e2d048d4b7ce");
        languageIdList.add("17417989-2c50-11ee-a171-e2d048d4b7ce");
        languageIdList.add("17417992-2c50-11ee-a171-e2d048d4b7ce");
        List<SastEngineConfigResp> resp = sastService.engineConfig(languageIdList);
        System.out.println(resp);
    }
    @Test
    public void detectionConfig(){
        SastDetectionConfigResp resp = sastService.detectionConfig("17417989-2c50-11ee-a171-e2d048d4b7ce");
        System.out.println(resp);
    }
    @Test
    public void applicationEcho(){
        System.out.println(sastService.getApplicationEcho("98776c27-0f8b-4884-abed-26b384008968"));
    }

    @Test
    public void applicationCreate(){
        SastApplicationEchoResp applicationEcho = sastService.getApplicationEcho("98776c27-0f8b-4884-abed-26b384008968");
        System.out.println(JSON.toJSONString(applicationEcho));

        SastApplicationCreateReq sastApplicationCreateReq = converter.converter(applicationEcho);
        List<String> list = applicationEcho.getLodeFiles().stream().map(SastApplicationEchoResp.LodeFile::getFileId).toList();
        sastApplicationCreateReq.setFileId(list);
        sastApplicationCreateReq.setApplicationId("98776c27-0f8b-4884-abed-26b384008968");
        System.out.println(JSON.toJSONString(sastApplicationCreateReq));
        SastApplicationCreateResp sastApplicationCreateResp = sastService.applicationCreate(sastApplicationCreateReq);
        System.out.println(JSON.toJSONString(sastApplicationCreateResp));
    }
    @Test
    public void reportDelete(){
        sastService.reportDelete("4af3380a-de08-476b-b1bc-b86f8d2e1339");
    }
    @Test
    public void reportDownload() throws MalformedURLException {
        String s = sastService.reportDownload("3300b586-52d7-4a46-b656-e653a0b2a024");
        URI uri = URI.create(s);
        URL url = uri.toURL();
        try (InputStream in = url.openStream()) {
            byte[] bytes = in.readAllBytes();
            String s1 = new String(bytes, StandardCharsets.UTF_8);
            System.out.println(s1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Test
    public void  jsonReport(){
        System.out.println(getReportJSON("23bc93d6-27df-4fd7-9ffa-5e4a518d6c57", "DETAILS"));
    }
    private String getReportJSON(String applicationId,String model){
        String reqJSON = "{\"mode\":\"DETAILS\",\"contacts\":\"admin@clouditera.com\",\"reportType\":\"APPLICATION\",\"format\":\"JSON\",\"projectId\":\"8a863857-bab3-40d9-a79a-2cb6617a9dd3\",\"applicationIds\":[\"9e3e55d6-6d28-4fd1-adc2-15b6cf0702db\"],\"bugLevels\":[\"DEADLY\",\"SEVERITY\",\"POOR_RISK\",\"LOW_RISK\"],\"audRiskLevels\":[\"WAITING\",\"IGNORE\",\"HIGH\",\"MEDIUM\",\"LOW\",\"NONE\"],\"applicationScope\":\"ALL\"}";
        SastReportCreateReq sastReportCreateReq = JSON.parseObject(reqJSON, SastReportCreateReq.class);
        sastReportCreateReq.setMode(model);
        sastReportCreateReq.setFormat(SastConstant.REPORT_FORMAT_JSON);
        sastReportCreateReq.setApplicationIds(Collections.singletonList(applicationId));
        log.info("获取JSON报告请求参数{}",JSON.toJSONString(sastReportCreateReq));
        String jsonReportUrl = sastService.reportIndex(sastReportCreateReq);
        log.info("获取JSON报告获得url{}",jsonReportUrl);
        return getJSONString(jsonReportUrl);
    }
    private String getJSONString(String reportId){
        String s = sastService.reportDownload(reportId);
        URI uri = URI.create(s);
        URL url = null;
        try {
            url = uri.toURL();
        } catch (MalformedURLException e) {
            log.info("sast 创建uri{}",uri);
            log.error("sast 获取json格式报告失败:",e);
        }
        try (InputStream in = url.openStream()) {
            byte[] bytes = in.readAllBytes();
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("获取json格式报告失败:",e);
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"获取JSON格式报告失败");
        }
    }
    @Test
    public void reportDownLoad(){
        JSONObject jsonObject = sastService.jsonReportDownload("3300b586-52d7-4a46-b656-e653a0b2a024");
        System.out.println(jsonObject);
    }
    @Test
    public void getReportStatus(){
        SastReportStatusResp reportStatus = sastService.getReportStatus("34cd37e6-70b8-4b93-8387-5f666de87264");
        System.out.println(reportStatus);
    }
}
