package com.imofan.android.basic.notification;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.imofan.android.basic.LogUtils;
import com.imofan.android.basic.MFStatInfo;
import android.content.Context;


/**
 * 推送工具类
 * @author user
 *
 */
public class MFPushUtils {
    
    private static int socketTimeout = 10*1000;
    /**
     * 以post请求
     * @param mfParameter 请求参数对象
     */
    static String pullMsgByPost(MFParameter mfParameter) {
        String url = "http://apns.imofan.com/pull/";
        StringBuilder sb = new StringBuilder(url);
        sb.append(mfParameter.getDevId());
        sb.append("/"+String.valueOf(mfParameter.getAppId()));
        sb.append("/"+String.valueOf(mfParameter.getTimeStamp()));
        sb.append("/"+String.valueOf(mfParameter.getMd5()));
        url = sb.toString();
        
        String jsonData = getJsonFromServer(url);
        return jsonData;
    }

    /**
     * 获取服务端的返回状态参数
     * @param uri
     * @param params
     * @return 
     */
    private static String getJsonFromServer(String uri) {
        LogUtils.writeLog("======获取推送服务 uri： "+uri);
        String message = null;
        HttpPost post=null;
        try {
        	post = new HttpPost(uri);
            HttpParams param = new BasicHttpParams();
            ConnManagerParams.setTimeout(param, socketTimeout);
            HttpConnectionParams.setSoTimeout(param, socketTimeout);
            HttpConnectionParams.setConnectionTimeout(param, socketTimeout);
            HttpConnectionParams.setTcpNoDelay(param, true);
            
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(param, schReg);
            DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, param);
            HttpResponse response = httpClient.execute(post);
            int responseStatusCode = response.getStatusLine().getStatusCode();
            if ((responseStatusCode == 201) || (responseStatusCode == 200)) {
                //获取数据成功
                message = EntityUtils.toString(response.getEntity(),"utf-8");
            }else{
                message = null;
            }

            //Log.v("ly", "message:"+message);
            LogUtils.writeLog("message:"+message);
        } catch (IOException e) {
            LogUtils.writeLog("======获取推送消息异常 IOException :"+ e.getMessage());
            message=null;
            e.printStackTrace();
        }catch (Exception e) {
            LogUtils.writeLog("======获取推送消息异常 Exception :"+e.getMessage());
            message = null;
            e.printStackTrace();
        } finally {
            post.abort();
        }
        return message;
    }
    
    
    /**
     * 解析推送内容
     * @param msgContent
     * @return
     */
    static List<MFMessage> parseJson(String msgContent){
        List<MFMessage> msgs = null;
        if(null!=msgContent && !"".equals(msgContent)){
            try {
                JSONObject jsonObject = new JSONObject(msgContent);
                JSONArray jsonArray = jsonObject.optJSONArray("messages");
                if(null!=jsonArray && jsonArray.length()>0){
                    msgs = new ArrayList<MFMessage>();
                    int length = jsonArray.length();
                    for(int i=0;i<length;i++){
                        MFMessage mfMessage = new MFMessage();
                        mfMessage.setAppId(jsonArray.optJSONObject(i).optString("app_id"));
                        mfMessage.setAppVersion(jsonArray.optJSONObject(i).optString("app_ver"));
                        mfMessage.setMsgContent(jsonArray.optJSONObject(i).optString("content"));
                        mfMessage.setLanguage(jsonArray.optJSONObject(i).optString("lang"));
                        mfMessage.setOsVersion(jsonArray.optJSONObject(i).optString("os_ver"));
                        mfMessage.setMsgId(jsonArray.optJSONObject(i).optInt("push_id"));
                        mfMessage.setTimeStamp(jsonArray.optJSONObject(i).optLong("ts"));
                        msgs.add(mfMessage);
                    }
                    
                }
            } catch (JSONException e) {
                msgs = null;
                e.printStackTrace();
            }
        }
        return msgs;
    }
    
    
    /**
     * 存储推送监听器的class 
     * @param listenerClass
     */
    public static void saveListenerCLass(Context context,Class listenerClass){
        if(null!=listenerClass){
            String listenerName = listenerClass.getName();
            if(null!=listenerName && !"".equals(listenerName)){
                MFPreferencesUtils.setPreferences(context, "mfpush", "pushListener", listenerName);
            }
        }
    }
    
    /**
     * 利用反射创建MFNotificationListener对象
     * @param context
     * @return
     */
    public static MFNotificationListener getNotificationListener(Context context){
        MFNotificationListener mfNotificationListener = null;
        String listenerName = MFPreferencesUtils.getPreference(context, "mfpush", "pushListener", "");
        if(listenerName != null && listenerName.trim().length() > 0) {
            try {
                mfNotificationListener = (MFNotificationListener)(Class.forName(listenerName).newInstance());
            } catch (IllegalAccessException e) {
                mfNotificationListener=null;
                e.printStackTrace();
            } catch (InstantiationException e) {
                mfNotificationListener=null;
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                mfNotificationListener=null;
                e.printStackTrace();
            }catch(ClassCastException e){
                mfNotificationListener=null;
                e.printStackTrace();
            }catch(Exception e){
                mfNotificationListener=null;
                e.printStackTrace();
            }
        } 
        return mfNotificationListener;
    }
    
    /**
     * 获取设备id
     * @param context
     * @return
     */
    static String getDevId(Context context){
        String devId = null;
        devId=MFPreferencesUtils.getPreference(context, MFStatInfo.INFO_FILE, MFStatInfo.KEY_DEV_ID, "");
        return devId;
    }
}
