package com.umeng.push.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class PushClient {
    
    // The user agent
    protected final String USER_AGENT = "Mozilla/5.0";

    private RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setSocketTimeout(2*60*1000)
            .setConnectTimeout(2*60*1000)
            .setConnectionRequestTimeout(2*60*1000)
            .build();
    
    private CloseableHttpClient client = HttpClients.custom()
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();
    
    // This object is used for sending the post request to Umeng
//    protected HttpClient client = new DefaultHttpClient();
    
    // The host
    protected static final String host = "http://msg.umeng.com";
    
    // The upload path
    protected static final String uploadPath = "/upload";
    
    // The post path
    protected static final String postPath = "/api/send";

    public String send(UmengNotification msg) {
        HttpPost post = null;
        BufferedReader rd = null;
        try {
            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.getAppMasterSecret()).getBytes("utf8"));
            url = url + "?sign=" + sign;
            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);
            int status = response.getStatusLine().getStatusCode();
            System.out.println("Response Code : " + status);
            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());
            
            JSONObject respJson = JSON.parseObject(result.toString());//new JSONObject(result.toString());
            String ret = respJson.getString("ret");
            if (status == 200 && "SUCCESS".equals(ret)) {
                
                return "SUCCESS";
            }
            return respJson.getJSONObject("data").getString("error_code");
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if(post != null){
                
                try {
                    post.clone();
                } catch (CloneNotSupportedException e) {}
            }
            if(rd != null){
                try {
                    rd.close();
                } catch (IOException e) {}
            }
        }
        return "FAILD";
    }

    // Upload file with device_tokens to Umeng
    public String uploadContents(String appkey,String appMasterSecret,String contents) {
        // Construct the json string
        try {
            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 + appMasterSecret).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 = JSON.parseObject(result.toString());//new JSONObject(result.toString());
            String ret = respJson.getString("ret");
            if (!ret.equals("SUCCESS")) {
                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;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

}
