package edu.lu.uni.serval.richedit.ediff;

import com.github.gumtreediff.tree.ITree;
import edu.lu.uni.serval.utils.EDiffHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.util.List;


/**
 * Parse fix violations with GumTree in terms of multiple statements.
 *
 * @author kui.liu
 */
public class EDiffHunkParser extends EDiffParser
{
    private static final Logger logger = LoggerFactory.getLogger(EDiffHunkParser.class);

    @Override
    public void parseFixPatterns(File prevFile, File revFile, File diffentryFile, String project, JedisPool innerPool, String srcMLPath, String hunkLimit, boolean isJava)
    {
        try
        {
            String[] split1 = diffentryFile.getParent().split(project);
            String pj = split1[1].split("/")[1];

            List<HierarchicalActionSet> actionSets = parseChangedSourceCodeWithGumTree2(prevFile, revFile, srcMLPath, isJava);

            if (actionSets != null && actionSets.size() != 0)
            {
                int hunkSet = 0;
                if (actionSets.size() <= Integer.parseInt(hunkLimit))
                {
                    for (HierarchicalActionSet actionSet : actionSets)
                    {
                        String astNodeType = actionSet.getAstNodeType();
                        actionSet.toString();
                        int size = actionSet.getActionSize();

                        String key = astNodeType + "/" + size + "/" + pj + "_" + diffentryFile.getName() + "_" + hunkSet;

                        ITree targetTree = EDiffHelper.getTargets(actionSet, isJava);
                        ITree actionTree = EDiffHelper.getActionTrees(actionSet);
                        ITree shapeTree = EDiffHelper.getShapeTree(actionSet, isJava);
                        ITree tokenTree = EDiffHelper.getTokenTree(actionSet, isJava);
                        String tokens = EDiffHelper.getNames2(tokenTree);
                        try (Jedis inner = innerPool.getResource())
                        {
                            inner.hset("dump", key, actionSet.toString());
                            inner.hset(key, "actionTree", actionTree.toStaticHashString());
                            inner.hset(key, "targetTree", targetTree.toStaticHashString());
                            inner.hset(key, "shapeTree", shapeTree.toStaticHashString());
                            inner.hset(key, "tokens", tokens);
                        }

                        hunkSet++;
                    }
                    try (Jedis inner = innerPool.getResource())
                    {
                        inner.hset("diffEntry", pj + "_" + diffentryFile.getName(), "1");
                    }
                }
            }
        }
        catch (Exception e)
        {
            logger.error("error", e);
        }
    }
}
