package cn.axzo.msg.center.inside.notices.service.umeng;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * api文档: <a href="https://developer.umeng.com/docs/67966/detail/68343">api文档</a>
 */
@Slf4j
public class PushClient {

  // The host
  protected static final String host = "http://msg.umeng.com";

  // This object is used for sending the post request to Umeng
  /* protected HttpClient client = new DefaultHttpClient();*/
  // The upload path
  protected static final String uploadPath = "/upload";
  // The post path
  protected static final String postPath = "/api/send";
  // The user agent
  protected final String USER_AGENT = "Mozilla/5.0";

  public boolean send(UmengNotification msg) throws Exception {

    String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
    msg.setPredefinedKeyValue("timestamp", timestamp);
    String url = host + postPath;
    String postBody = msg.getPostBody();
    String sign = DigestUtils
        .md5Hex(("POST" + url + postBody + msg.getCmpAndroidSecret()).getBytes("utf8"));
    url = url + "?sign=" + sign;
    cn.hutool.http.HttpResponse response = null;
    try {
      response = HttpUtil.createPost(url).header("User-Agent", USER_AGENT)
          .body(postBody).execute().charset("utf-8");
    } finally {
      int status = -1;
      String result = null;
      if (response != null) {
        status = response.getStatus();
        result = response.body();
      }
      log.info("send push finish. phoneType={}, url={}, postBody={}, responseCode={}, responseBody={}, isSuccess={}",
              msg.getClass().getSimpleName(), url, postBody, status, result, status == 200);
    }
    return true;
  }

  // Upload file with device_tokens to Umeng
 /* public String uploadContents(String appkey, String CmpAndroidSecret, String contents)
      throws Exception {
    // Construct the json string
    JSONObject uploadJson = new JSONObject();
    uploadJson.put("appkey", appkey);
    String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
    uploadJson.put("timestamp", timestamp);
    uploadJson.put("content", contents);
    // Construct the request
    String url = host + uploadPath;
    String postBody = uploadJson.toString();
    String sign = DigestUtils.md5Hex(("POST" + url + postBody + CmpAndroidSecret).getBytes("utf8"));
    url = url + "?sign=" + sign;
    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", USER_AGENT);
    StringEntity se = new StringEntity(postBody, "UTF-8");
    post.setEntity(se);
    // Send the post request and get the response
    HttpResponse response = client.execute(post);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }
    System.out.println(result.toString());
    // Decode response string and get file_id from it
    JSONObject respJson = new JSONObject(result.toString());
    String ret = respJson.getString("ret");
    if (!"SUCCESS".equals(ret)) {
      throw new Exception("Failed to upload file");
    }
    JSONObject data = respJson.getJSONObject("data");
    String fileId = data.getString("file_id");
    // Set file_id into rootJson using setPredefinedKeyValue

    return fileId;
  }*/

}
