package com.cloudbillity.sendsms;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import com.alibaba.fastjson.JSON;

@WebServlet(urlPatterns = { "/send", "/send/" })
public class SmsServlet extends javax.servlet.http.HttpServlet {

	// 行云管家管理控制台 OpenAPI中的AccessKey信息，需要更换为实际的AccessKey
	private String accessKeySecret = "";
	private String shellPath = "/opt/sendmessage";

	@Override
	public void init() throws ServletException {
		super.init();
		String fileName = shellPath + "/config.properties";
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(fileName);
			bufferedReader = new BufferedReader(fileReader);
			accessKeySecret = bufferedReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
				fileReader.close();
			} catch (IOException e) {
			}
		}
	}

	@Override
	protected void doPost(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 版本
		String version = request.getParameter("version");
		// 本次调用签名值
		String signature = request.getParameter("signature");
		// 行云管家管理控制台 OpenAPI中的AccessKey信息
		String accessKeyId = request.getParameter("accessKeyId");

		Map<String, Object> signMap = new HashMap<String, Object>();
		signMap.put("timestamp", timestamp);
		signMap.put("version", version);
		signMap.put("nonce", nonce);
		signMap.put("accessKeyId", accessKeyId);

		// 通过工具类生成签名，与请求中携带的签名值进行比较，看是否相同
		String signature0 = SignUtil.sign(null, signMap, "POST", accessKeySecret);

		Map<String, Object> result = new HashMap<String, Object>();
		if (signature == null) {
			result.put("success", false);
			result.put("msg", "签名失败");
			System.out.println("签名失败");
		} else if (signature.equals(signature0)) {
			// 签名校验成功
			// body为短信模版参数，拿到参数去自有短信平台发送短信
			BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
			ByteArrayOutputStream buf = new ByteArrayOutputStream();
			int r = bis.read();
			while(r != -1) {
			    buf.write((byte) r);
			    r = bis.read();
			}
			// StandardCharsets.UTF_8.name() > JDK 7
			String jsonString =  buf.toString("UTF-8");
			
			//System.out.println("json is:"+jsonString);
			SmsRequest body = JSON.parseObject(jsonString, SmsRequest.class, null);
			result.put("success", true);
			result.put("msg", "签名成功");
			// 短信内容
			String smsText = body.getSMSText();
			// 接收短信的手机号码列表
			List<String> pns = body.getPhones();
			// --------在这里调用您的业务代码，进行短信发送即可---------- start //
			for (String pn : pns) {
				String cmd = shellPath + "/sendmessage.sh \"" + smsText + "\" " + pn;
				ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd);
				builder.directory(new File(shellPath));
				builder.start();
				result.put("success", true);
				System.out.println("success");
			}
			// --------在这里调用您的业务代码，进行短信发送即可---------- end //
		} else {
			// 签名校验失败，非行云管家平台发送请求
			result.put("success", false);
			result.put("msg", "签名失败");
			System.out.println("签名失败");
		}
		//out.println(JSON.toJSON(JSON.toJSONString(result)));
		out.println(JSON.toJSONString(result));
		out.flush();
		out.close();
	}

	@Override
	protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
			throws javax.servlet.ServletException, IOException {
		this.doPost(request, response);
	}
}
