package com.imofan.android.basic.notification;
import java.util.List;

import com.imofan.android.basic.LogUtils;
import com.imofan.android.basic.Mofang;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

/**
 * 消息推送服务
 * @author liyang
 *
 */
public class MFPNService extends Service{
    
    private static final String TAG = MFPNService.class.getSimpleName();
    //PUBLISH CHECK
    private static final long intervalAlarmTime = 300000;//定时器，5分钟
//    private static final long intervalAlarmTime = 60000;//定时器，测试1分钟
    private static PowerManager.WakeLock wakeLock;
    
    //消息状态
    private final int MESSAGE_PUSH_SUCCEED = 1;
    private static PendingIntent pendingIntent = null;
    private long messageLatestTime; //服务器最新消息时间
    
    private Handler messagePushHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case MESSAGE_PUSH_SUCCEED:
                    // 获取推送消息成功
                	List<MFMessage> msgList;
                	Object object = msg.obj;
                	if(object!=null){
                		msgList = (List<MFMessage>) msg.obj;
                	}else{
                		msgList = null;
                	}
                	
                    //回调接口中的函数,将获取到符合规则的消息传递给开发者
                    //if(null!=msgList && !msgList.isEmpty()){
                        //获取推送监听器对象
                        MFNotificationListener mfNotificationListener=MFPushUtils.getNotificationListener(getApplicationContext());
                        LogUtils.writeLog("======准备发送消息到客户端 mfNotificationListener ："+mfNotificationListener);
                        if(null!=mfNotificationListener){
                            mfNotificationListener.onNotificationReceived(getApplicationContext(),msgList);
                        }
                    //}
                    break;
                default:
                    break; 
            }
            releaseWakeLock();
            stopSelf();
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent==null){
            try{                
                //如果被退出异常打断服务，重新广播一次
                Intent broadCastIntent = new Intent("com.imofan.android.basic.notification.MFAlarmReceiver");
                sendBroadcast(broadCastIntent);
            }catch(Exception e){
                e.printStackTrace();
            }
            return super.onStartCommand(intent, flags, startId);
        }
        
        //催醒手机，回复线程运行和网络
        acquireWakeLock(MFPNService.this);
        
        //初始化本地状态时间戳
        messageLatestTime = MFPreferencesUtils.getPreference(this, "message", "latestTime", 0l);
        
        //Log.v(TAG, "onStartCommand");
        LogUtils.writeLog("======启动推送服务");
        
        //开启新线程从服务器取消息状态，是否有最新推送消息，如果有，推送信息是什么
        Thread messageThread = new Thread(new MessagePushRunnable());
        messageThread.start();
       
        return super.onStartCommand(intent, flags, startId);
    }
    
    
    private class MessagePushRunnable implements Runnable{
        public void run() {
            Message msg = null;
            //消息对象
            MFMessage mfMessage = null;
            //获取服务端推送的消息
            String jsonContent = getPushContent();
            
            //解析获取的json数据
            List<MFMessage> msgs = MFPushUtils.parseJson(jsonContent); 
            
            //获取解析数据中时间戳最大的消息对象
            //mfMessage = MFPushUtils.getMaxTsMsg(getApplicationContext(),msgs);
            //if(null!=msgs){
                msg = messagePushHandler.obtainMessage();
                msg.obj = msgs;
                msg.what = MESSAGE_PUSH_SUCCEED;
                messagePushHandler.sendMessage(msg);
            //}else{
            //    releaseWakeLock();
            //    stopSelf();
            //}
        }
    }
    
    /**
     * 获取设备DevId
     * @param context
     * @return
     */
    public static String getDevId(Context context){
        return MFPushUtils.getDevId(context);
    }
    
    /**
     * 获取服务器端最新的推送消息
     */
    private String getPushContent(){
        String message = null;
        MFParameter mfParameter = new MFParameter();
        //获取appkey
        String appKey = Mofang.getAppKey(getApplicationContext());
        Log.v(TAG,"AppKey: "+appKey);
        String devID = MFPushUtils.getDevId(getApplicationContext());
        Log.v(TAG, "DevId: " +devID);
        //如果appkey或者devId为空释放CPU的锁
        if(null==appKey || null==devID){
            releaseWakeLock();
            return null;
        }
        long appId = Long.valueOf(appKey.substring(appKey.length() - 8), 16);
        Log.v(TAG, "AppId: " + appId);
        mfParameter.setDevId(devID);
        mfParameter.setAppId(appId);
        Log.v(TAG, "LatestTime：" + messageLatestTime);
        mfParameter.setTimeStamp(messageLatestTime);
        Log.v(TAG, "MD5: " + MFParameter.getMd5Verify(getApplicationContext(), appId,messageLatestTime));
        mfParameter.setMd5(MFParameter.getMd5Verify(getApplicationContext(), appId,messageLatestTime));
        //以post方式请求
        message = MFPushUtils.pullMsgByPost(mfParameter);
        return message;
    }
    
    /**
     * 开启定时推送服务
     * @param context
     * @param listenerClass  推送监听器的Class
     */
    public static void startPushService(Context context,Class listenerClass){
        String devId = MFPushUtils.getDevId(context);
        //Log.v(TAG, "devId : "+devId);
        if(null!=listenerClass){
            //存储listenerClass
            MFPushUtils.saveListenerCLass(context,listenerClass);
        
        }
        if(null!=devId && !"".equals(devId)){
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
            Intent intent = new Intent(context,MFAlarmReceiver.class);  
            if(null!=pendingIntent){ 
                //取消前面之前已经过时的 定时器
                alarmManager.cancel(pendingIntent);
            }
            pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            //设置新的定时器：类型，开始时间，间隔时间，定时触发的intent
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), intervalAlarmTime, pendingIntent);
            //Log.v(TAG, "定时器设置完毕");
            LogUtils.writeLog("======推送定时器启动");
        }
    }
    
    /**
     * 停止定时推送服务
     * @param context
     */
    public static void stopPushService(Context context){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService("alarm");
        if(null!=pendingIntent){
            alarmManager.cancel(pendingIntent);
            pendingIntent= null;
        }
    }
    
    /**
     * 设置推送开关
     * @param context
     * @param status (true:打开推送，false:关闭推送)
     */
    public static void setPushStatus(Context context,boolean status){
        MFPreferencesUtils.setPreferences(context, "push", "status", status);
    }

    /**
     * 唤醒服务
     * @param context
     */
    private static void acquireWakeLock(Context context){
        if(wakeLock!=null){
            //已经催醒
            return;
        }
        PowerManager powerManager = (PowerManager)(context.getSystemService(Context.POWER_SERVICE));
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();
    }
    
    /**
     * 释放唤醒
     */
    private static void releaseWakeLock(){
        if(wakeLock!=null&&wakeLock.isHeld()){
            wakeLock.release();
            wakeLock = null;
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseWakeLock();
    }
}
