package com.zjty.inspect.utils;

import com.zjty.inspect.dao.MasterRuleDao;
import com.zjty.inspect.entity.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Component
public class AnalysisFile {

    private HashMap<String, MasterRule> ruleMap = new HashMap<String, MasterRule>();

    @Autowired
    private MasterRuleDao ruleDao;

    public static List<PomDependency> analysisGradle(Path pomPath) {
        List<String> strings = null;
        try {
            strings = Files.readAllLines(pomPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<PomDependency> dependencies = new ArrayList<>();
        for (String string : strings) {
            if(string.indexOf("compile")>0){
                PomDependency pomDependency = new PomDependency();
                int compile = string.indexOf("compile");
                int i = compile + 9;
                String substring = string.substring(i);
                String[] split = substring.split(":");
                pomDependency.setGroupId(split[0]);
                pomDependency.setArtifactId(split[1]);
                dependencies.add(pomDependency);
            }
        }
        return dependencies;
    }

    public DepTreePom parseTreeFile(String reportId, String filePath, List<MasterRule> ruleList, String techId) {
        ArrayList<MasterRule> rules = new ArrayList<>();
        HashMap<String, String> map1 = new HashMap<>();
        ArrayList<Warn> warns = new ArrayList<>();
        Path path = Paths.get(filePath);
        DepTreePom depTreePom = new DepTreePom();
        HashMap<Integer, DepTree> map = new HashMap<>();
        int one = 1;
        DepTree depTree = new DepTree();
        depTreePom.setDepTree(depTree);
        try {
            List<String> strings = Files.readAllLines(path);
            String s1 = strings.get(0);

            map.put(0,depTree);
            int now = 0;
            depTree.setDepName(s1);
            for (int i = 1; i <= strings.size()-1; i++) {
                DepTree depTree1 = new DepTree();
                String s = strings.get(i);
                int i1 = s.indexOf("-");
                String s2 = s.substring(i1 + 1).replaceAll("\\|", "").replaceAll("\\+", "")
                        .replaceAll(" ", "")
                        .replaceAll("\\\\", "");

                if(i1==one){
                    depTree1.setDepName(s2);
                    depTree.getDepTreeList().add(depTree1);
                }else{
                    if(i1>now){
                        depTree1.setDepName(s2);
                        map.get(i1).getDepTreeList().add(depTree1);
                    }else{
                        depTree1.setDepName(s2);
                        map.get(i1).getDepTreeList().add(depTree1);
                    }
                }

                for (MasterRule rule : ruleList) {
                    if(KmpUtil.kmpMatch(s,rule.getTarget())>0){
                        depTree1.setViolation(1);
                        depTreePom.add(rule.getTechnologyId());
                        //rule匹配上了
                        Warn warn = new Warn();
                        warn.setFilePath(filePath);
                        warn.setLineNum(i);
                        warn.setTechnologyId(rule.getTechnologyId());
                        warn.setRuleId(rule.getId());
                        warns.add(warn);
                    }
                }
                map.put(i1+3,depTree1);
                now = i1;
                //将依赖全部放进规则库中
                String[] split = s2
                        .split(":");
                StringBuilder stringBuffer = new StringBuilder();
                for (int i2 = 0; i2 < 2; i2++) {
                    if(stringBuffer.length()==0){
                        stringBuffer.append(split[i2]).append(":");
                    }else{
                        stringBuffer.append(split[i2]);
                    }
                }
                map1.put(stringBuffer.toString(),"");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        Set<String> strings = map1.keySet();
        for (String string : strings) {
            StringBuilder append = stringBuilder.append(string).append(":").append(techId);
            if(!ruleMap.containsKey(append.toString())){
                MasterRule rule1 = new MasterRule();
                rule1.setId(UUIDUtil.getUUID());
                rule1.setTechnologyId(techId);
                rule1.setTarget(string);
                rule1.setSuffix("xml");
                rules.add(rule1);
                MasterRule rule2 = new MasterRule();
                rule2.setId(UUIDUtil.getUUID());
                rule2.setTechnologyId(techId);
                rule2.setTarget(string);
                rule2.setSuffix("gradle");
                rules.add(rule2);
                ruleMap.put(append.toString(),rule1);
            }
            append.delete(0,append.length());
        }
        ruleDao.saveAll(rules);
        return depTreePom;
    }

    public void setMap(HashMap<String, MasterRule> map){
        this.ruleMap=map;
    }


    public ProjectPom analysisPom(Path pomPath){
        ProjectPom projectPom = new ProjectPom();
        List<PomDependency> dependencies = new ArrayList<>();
        Document document = null;
        try {
            document = DocumentHelper.parseText(new String(Files.readAllBytes(pomPath)));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element rootElement = document.getRootElement();

        Element dependencies1 = rootElement.element("dependencies");
        if(dependencies1!=null){
            List<Element> dependency = dependencies1.elements("dependency");
            for(Element element:dependency){
                PomDependency pomDependency = new PomDependency();
                pomDependency.setGroupId(element.elementText("groupId"));
                pomDependency.setArtifactId(element.elementText("artifactId"));
                dependencies.add(pomDependency);
            }
        }
        projectPom.setDependencies(dependencies);
        return projectPom;
    }

    public static void main(String[] args) {
        String string = "   compile 'com.spring.test:spring-core:4.25'";
        String[] split = string.split(":");
        if(string.indexOf("compile")>-1){
            PomDependency pomDependency = new PomDependency();
            int compile = string.indexOf("compile");
            int i = compile + 9;
            String substring = string.substring(i);
            String[] split1 = substring.split(":");
            System.out.println(split1[0]);
            System.out.println(split1[1]);
            pomDependency.setGradle(substring);
        }

    }
}
