package com.eactive.kakao.rolling.servlet;

import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.http.HttpServlet;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpRequest;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpResponse;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.kakao.rolling.CurrentCommitIdService;
import com.eactive.kakao.rolling.TableSuffixResolver;

public class RollingServlet extends HttpServlet {
	static final SocketAdapterManager manager = SocketAdapterManager.getInstance();
    static Logger logger = SocketLoggerManager.getInstance().getLogger("FileLogger{NET}_HTTP");

    protected void doService(HttpRequest request, HttpResponse response) throws Exception {
        String command = request.getContext();
         if (command.lastIndexOf('/') == -1) {
            command = "";
         } else {
            command = command.substring(command.indexOf('/')+1);
         }
         String result = "";
         
         try {
            if (command == null || "".equals(command) || "commitid".equals(command)) {
               result = getCommitId();
            } else if ("suffix".equals(command)) {
               result = getSuffix();
            } else {
               response.setResponseCode(404);
               return;
            }
        } catch(Throwable e) {
           result = "{ \"error\" : \"" + e.getMessage() + "\"}";
        }     
        
        response.setContentType("application/json;charset=utf-8");
        response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
        response.appendBody(result);
     }
     private String getCommitId() throws Exception {
        CurrentCommitIdService service = ApplicationContextProvider.getContext().getBean(CurrentCommitIdService.class);
        String commitId = service.getSystemCommitId();
        
        StringBuffer sb = new StringBuffer();
        sb.append("{\"commitId\" : \"").append(commitId).append("\"}");
         return sb.toString();
     }
     private String getSuffix() throws Exception {
        TableSuffixResolver service = ApplicationContextProvider.getContext().getBean(TableSuffixResolver.class);
        String suffix = service.getCurrentSuffix();
        StringBuffer sb = new StringBuffer();
        sb.append("{\"suffix\" : \"").append(suffix).append("\"}");
         return sb.toString();
     }	
}
