package org.bdware.sc.handler;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.operations.BasicOperations;
import org.bdware.doip.endpoint.server.DoipRequestHandler;
import org.bdware.doip.endpoint.server.NettyServerHandler;
import org.bdware.doip.endpoint.server.RepositoryHandler;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.hook.DOOPHandler;
import org.bdware.sc.entity.DoipMessagePacker;
import org.bdware.sc.node.FunctionNode;

import java.util.HashMap;
import java.util.Map;

public class DOOPRequestHandler implements DoipRequestHandler, RepositoryHandler {
    public Map<String, FunctionNode> doipOperationsMap;
    static Logger logger = LogManager.getLogger(NettyServerHandler.class);
    Gson gson;

    public static DOOPRequestHandler instance;

    public DOOPRequestHandler() {
        if(instance == null) {
            instance = new DOOPRequestHandler();
            instance.doipOperationsMap = new HashMap<>();
            gson = new Gson();
        }
    }

    public void addDoipOperation(FunctionNode function) {
        doipOperationsMap.put(function.getDoipOperationInfo().operationName, function);
    }

    @Override
    public DoipMessage onRequest(ChannelHandlerContext ctx, DoipMessage msg) {
        String str = msg.header.parameters.operation;
        logger.debug("[Call operation] name: " + str);
        if (str != null) {
            FunctionNode fn;
            fn = doipOperationsMap.get(str);
            if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
            if (fn != null) {
                return buildRequestAndInvokeEngine(fn, msg);
            }
        }
        return null;
    }

    @Override
    public DoipMessage handleHello(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.Hello.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    @Override
    public DoipMessage handleListOps(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.ListOps.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    @Override
    public DoipMessage handleCreate(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.Create.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    @Override
    public DoipMessage handleUpdate(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.Update.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    @Override
    public DoipMessage handleDelete(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.Delete.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    @Override
    public DoipMessage handleRetrieve(DoipMessage request) {
        FunctionNode fn = doipOperationsMap.get(BasicOperations.Retrieve.getName());
        if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
        if (fn != null) {
            return buildRequestAndInvokeEngine(fn, request);
        }
        return null;
    }

    public DoipMessage buildRequestAndInvokeEngine(FunctionNode fn, DoipMessage msg) {
        ContractRequest contractRequest = constructContractRequest(fn, msg);
        DoipMessagePacker arg = new DoipMessagePacker("doip", msg);
        try {
            // 改变调用的函数 + 构造DoipMessagePacker
            Object ret = ContractProcess.instance.engine.executeWithoutLock(fn, contractRequest, arg);
            return DOOPHandler.convertJsonElementToDoipMessage((JsonElement) ret, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public ContractRequest constructContractRequest(FunctionNode fn, DoipMessage request) {
        ContractRequest cr  = new ContractRequest();
        cr.setContractID("");
        cr.setRequester(request.credential.getSigner());
        cr.setAction(fn.functionName);
        return cr;
    }
}
