package org.bdware.sc.engine.hook;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.ProjectConfig;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;

public class MaskHandler implements AnnotationHook {
    private static final Logger LOGGER = LogManager.getLogger(MaskHandler.class);

    @Override
    public Object handle(ContractRequest input, JSEngine Engine, Object ret) {
        try {
            DesktopEngine desktopEngine = (DesktopEngine) Engine;
            ProjectConfig projectConfig = desktopEngine.getProjectConfig();
            JsonElement maskConf = projectConfig.getMask(input.getAction());
            if (null != maskConf) {
                LOGGER.debug("execute maskConf: " + maskConf);
                String s1 = ret.toString();
                //budeijin
                //"{\"count\":1}"
                //{"count":1}
                //System.out.println(s1);
                s1 = s1.replace("\\", "");
                s1 = s1.substring(1, s1.length() - 1);
                //System.out.println(s1);
                //System.out.println(JsonParser.parseString(s1));
                MaskVisitor visitor = new MaskVisitor(JsonParser.parseString(s1));
                visitor.visit(maskConf);
                ret = visitor.get();
                LOGGER.debug(maskConf);
                if (null != ret) {
                    return ret;
                }
                ret = JsonParser.parseString("");
            }
            return ret;
        } catch (Exception e) {
            // e.printStackTrace();
            return ret;
        }
    }

    public Object getMaskResult(JsonElement maskConfigInvoke, JsonElement data) {
        if (null == maskConfigInvoke || maskConfigInvoke.getAsString().isEmpty()) {
            return data;
        }
        MaskVisitor visitor = new MaskVisitor(data);
        visitor.visit(maskConfigInvoke);
        JsonElement root = visitor.get();
        LOGGER.info("MaskRetInvoke: " + root);
        return root;
    }
}
