package leigh.esp.goryu.service;

import leigh.eo.EO;
import leigh.eo.json.JsonInput;
import leigh.eo.json.JsonOutput;
import leigh.esp.goryu.engine.TransactionProcessor;
import leigh.esp.sdk.service.MicroService;
import leigh.esp.sdk.service.schema.v1.MicroServiceCfgElementDAO;
import leigh.mecha.http.server.WebTransaction;
import org.apache.commons.dbcp.BasicDataSource;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

public class GoryuService extends MicroService {
    private final BasicDataSource dataSource;

    public GoryuService(EO cfg, BasicDataSource dataSource) throws IOException {
        super(cfg);
        this.dataSource = dataSource;
    }

    @Override
    public void serviceRequest(WebTransaction request) throws Throwable {
        JsonInput input = new JsonInput(request.httpServletRequest.getInputStream());
        try (Connection con = dataSource.getConnection()) {
            TransactionProcessor tp = new TransactionProcessor();
            try (JsonOutput output = new JsonOutput(request.httpServletResponse.getOutputStream())) {
                tp.process(con, input, output);
            }
        }
    }

    public static void main(String args[]) throws IOException {
        Properties p = new Properties();
        p.load(new FileInputStream("test.properties"));
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://db1.leigh-co.com/aleigh_test");
        dataSource.setUsername("aleigh");
        dataSource.setPassword(String.valueOf(p.get("db1_password")));

        EO cfg = MicroServiceCfgElementDAO.create();
        MicroServiceCfgElementDAO.setKabeUrl(cfg, "https://leigh-co.com/");
        MicroServiceCfgElementDAO.setSrcUri(cfg, "/goryu_test");
        GoryuService svc = new GoryuService(cfg, dataSource);
        svc.run();
    }
}
