package com.sagacloud.dev;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.utils.Calculator;
import com.sagacloud.utils.DpUtils;

/**
 * 开发人员使用，调试维护辅助接口 
 */
@Path("dev")
public class DevMaintain {
	private static List<String> configInfoList = new ArrayList<>();
	
	/**
	 * 获取配置文件信息
	 * @return
	 */
	@Path("/showConfig")
    @GET
    @Produces("text/html;charset=UTF-8")
    public String showConfig() {
		if(configInfoList.isEmpty()) {
			try {
				InputStream is = DevMaintain.class.getClassLoader().getResourceAsStream("config.properties");
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String temp = null;
				while ((temp = br.readLine()) != null) {
					configInfoList.add("<p>"+temp+"</p>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		StringBuffer htmlContent = new StringBuffer();
		htmlContent.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>configInfo</title></head><body>");
		for(String pStr : configInfoList) {
			htmlContent.append(pStr);
		}
		htmlContent.append("</body></html>");
		
		return htmlContent.toString();
    }
	
	/**
	 * 查看点位表达式计算结果
	 * @param expr 点位表达式，如(a+b)/2
	 * @return
	 */
	@Path("/calPointExp")
	@POST
    @Produces(MediaType.APPLICATION_JSON)
    public String calPointExp(String jsonStr) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		String expr = json.getString("expr");
		
		String errorMsg = "";
		try {
			String[] strAray = new Calculator().readExpression(expr);
			JSONArray content = new JSONArray(Arrays.asList(strAray));
			return DpUtils.successJsonResp("", content).toString();
		}catch (Exception e) {
			errorMsg = e.getMessage();
		}
		
		return DpUtils.errorJsonMsg(errorMsg);
    }
}
