package com.github.cjm0000000.kvstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.cjm0000000.kvstore.model.QueryRlt;
import com.github.cjm0000000.kvstore.service.Cache;
import com.github.cjm0000000.kvstore.service.impl.HeapCache;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by bl04904 on 2016/3/29.
 */
public class KvServlet extends HttpServlet {
    private static final long serialVersionUID = 8433669357081508585L;
    private static final String ENCODING = "UTF-8";
    private static final Logger apiCallLogger = LoggerFactory.getLogger("API_CALL");
    private static final Logger logger = LoggerFactory.getLogger(KvServlet.class);
    private Cache cache = new HeapCache(200_0000);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long s1 = System.nanoTime();
        String body = getKeys(req);
        long s2 = System.nanoTime();
        List<String> keys = JSON.parseArray(body, String.class);
        long s22 = System.nanoTime();
        resp.setContentType("application/json;charset=UTF-8");
        if(keys == null) {
            resp.getWriter().print("[]");
            return;
        }
        long s3 = System.nanoTime();
        List<QueryRlt> result = cache.get(keys);
        long s4 = System.nanoTime();
        apiCallLogger.info("bestQuery");
        long s5 = System.nanoTime();
        String r = JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
        long s6 = System.nanoTime();
        resp.getWriter().print(r);
        long s7 = System.nanoTime();
        logger.info("get params={} ms, fromJson={} ms, query={} ms, toJson={} ms, out={} ms.", (s2-s1)/1000000.0, (s22-s2)/1000000.0, (s4-s3)/1000000.0, (s6-s5)/1000000.0, (s7-s6)/1000000.0);
    }

    private String getKeys(HttpServletRequest req){
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(req.getInputStream(), writer, ENCODING);
            return writer.toString();
        } catch (Exception ex){
            // ignore
        }
        return null;
    }

    private String getKeys2(HttpServletRequest req) {
        try (BufferedReader br = req.getReader()){
            StringBuilder response = new StringBuilder(3000);
            String line;

            while((line=br.readLine()) != null){
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            // ignore
        }
        return null;
    }

    @Override
    public void init() throws ServletException {
        cache.initialize();
    }
}
