package org.bdware.sc.contractexample;

import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.irp.irplib.core.IrpMessage;
import org.bdware.irp.irplib.core.IrpMessageCode;
import org.bdware.irp.irplib.core.IrpRequest;
import org.bdware.irp.irplib.core.IrpResponse;
import org.bdware.irp.irpserver.IrpHandler;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class IrsHandler implements IrpHandler {
    static Logger LOGGER = LogManager.getLogger(IrsHandler.class);
    private final Resolver resolver;

    public IrsHandler(Resolver resolver) {
        this.resolver = resolver;
    }

    private Map<String, String> jsonToMap(JsonObject result) {
        Map<String, String> ret = new HashMap<>();
        for (String key : result.keySet()) ret.put(key, result.get(key).toString());
        return ret;
    }


    //TODO RETURN newDelegateRouterResponse instead
    @Override
    public IrpMessage batchCreateDOID(IrpMessage request) {
        return IrpResponse.newErrorResponse(IrpMessageCode.OC_BATCH_CREATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
    }

    //for any input, fix it to scheme://prefix/suffix format.
    public String fixScheme(String doid) {
        if (!doid.contains(":")) {
            doid = resolver.config.scheme + ":" + "//" + doid;
        } else {
            if (doid.contains(":") && !doid.contains(":/"))
                doid = doid.replace(":", "://");
            if (doid.contains(":/") && !doid.contains("://")) {
                doid = doid.replace(":/", "://");
            }
        }
        return doid;
    }

    @Override
    public IrpMessage resolveDOID(IrpMessage request) {
        try {
            LOGGER.info(request);
            IrpRequest req = (IrpRequest) request;
            String doid = req.getDoid();
            // support old resolve request in irp-sdk 1.0.1
            doid = fixScheme(doid);
            if (!doid.matches(".*://.*")) {
                return IrpResponse.newErrorResponse(IrpMessageCode.OC_RESOLUTION_DOID, IrpMessageCode.RC_ERROR, "unknown scheme");
            } else {
                String[] domainAndID = doid.split("://");
                if (domainAndID[0].equals(resolver.config.scheme)) {
                    String[] prefixAndSufix = domainAndID[1].split("/");
                    if (prefixAndSufix[0].equals(resolver.config.prefix)) {
                        JsonObject jsonObject = resolveInternal(prefixAndSufix[1]);
                        //TODO connect and respon.
                        Map<String, String> keypair = new HashMap<>();
                        for (String key : jsonObject.keySet()) {
                            if (!key.equals("sm2keypair"))
                                keypair.put(key, jsonObject.get(key).toString());
                        }
                        return IrpResponse.newIrsResolveResponse(domainAndID[1], keypair);
                    } else
                        return IrpResponse.newDelegateRouterResponse(resolver.config.upperRouter);
                } else {
                    return IrpResponse.newDelegateRouterResponse(resolver.config.upperRouter);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return IrpResponse.newErrorResponse(IrpMessageCode.OC_RESOLUTION_DOID, IrpMessageCode.RC_ERROR, fromException(e));
        }
    }

    public static byte[] fromException(Exception e) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(bo));
        return bo.toByteArray();
    }


    @Override
    public IrpMessage createDOID(IrpMessage request) {
        return IrpResponse.newErrorResponse(IrpMessageCode.OC_CREATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
    }

    @Override
    public IrpMessage updateDOID(IrpMessage request) {
        return IrpResponse.newErrorResponse(IrpMessageCode.OC_UPDATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
    }

    @Override
    public IrpMessage deleteDOID(IrpMessage request) {
        return IrpResponse.newErrorResponse(IrpMessageCode.OC_DELETE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
    }

    @Override
    public IrpMessage verifyIrs(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage resolvePrefix(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage createPrefix(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage updatePrefix(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage deletePrefix(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage verifyChildRouter(IrpMessage request) {
        return null;
    }

    @Override
    public IrpMessage queryIdentifierByOffset(IrpMessage request) {
        return null;
    }


    public JsonObject resolveInternal(String appName) {
        try {
            //load info from db
            Connection conn = Storage.instance.getDBConnection();
            Statement stmt = conn.createStatement();
            ResultSet result = stmt.executeQuery("select * from app where name = '" + appName + "';");
            JsonObject ele = parseFirstElementInResultSet(result);
            result.close();
            if (ele == null) {
                return null;
            }
            ele.remove("cover");
            System.out.println("[GDRouter] resolve step1:" + ele.toString());

            stmt = conn.createStatement();
            result = stmt.executeQuery("select * from contract where \"appId\" = " + ele.get("id").getAsInt() + ";");
            JsonObject ele2 = parseFirstElementInResultSet(result);
            result.close();
            if (ele2 != null && ele2.has("name"))
                ele.add("contractName", ele2.get("name"));
            System.out.println("[GDRouter] resolve step2:" + ele.toString());
            return ele;
        } catch (Exception e) {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(bo));
            JsonObject result = new JsonObject();
            result.addProperty("msg", new String(bo.toByteArray()));
            System.out.println("[GDRouter] resolve exception:" + result.toString());

            return result;
        }
    }

    private JsonObject parseFirstElementInResultSet(ResultSet result) throws SQLException {
        ResultSetMetaData meta = result.getMetaData();
        boolean hasElement = result.next();
        if (!hasElement) {
            return null;
        }
        JsonObject ele = new JsonObject();
        for (int j = 1; j <= meta.getColumnCount(); j++) {
            int type = meta.getColumnType(j);
            switch (type) {
                case -6:
                case 5:
                case 4:
                    ele.addProperty(meta.getColumnName(j), result.getInt(j));
                    break;
                case -5:
                    ele.addProperty(meta.getColumnName(j), result.getLong(j));
                    break;
                case 6:
                case 7:
                case 8:
                    ele.addProperty(meta.getColumnName(j), result.getDouble(j));
                    break;
                default:
                    ele.addProperty(meta.getColumnName(j), result.getString(j));
                    break;

            }
        }
        return ele;
    }
}
