/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.common.gcm.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;

import com.ntels.kneet.v3.common.gcm.support.GcmRegLocalBroadCast;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import java.util.ArrayList;
/**
 * <pre>
 * Push Main Servie
 * </pre>
 *
 * @author Sangtae
 * @since 2014. 3. 7. 오전 10:55:52
 */
public class PushService extends Service implements GCMRegistrater.onGCMRegistraterListener {

    private GcmSharedPreferences mGcmSharedPreferences;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    int                  mValue   = 0;

    public static final int REGISTER_CLIENT = 1;

    public static final int UNREGISTER_CLIENT = 2;

    public static final int MSG_SET_VALUE = 3;

    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {

        @Override public void handleMessage(Message msg) {

            switch (msg.what) {
                case REGISTER_CLIENT:
                    mClients.add(msg.replyTo);
                    break;
                case UNREGISTER_CLIENT:
                    mClients.remove(msg.replyTo);
                    break;
                case MSG_SET_VALUE:
                    mValue = msg.arg1;
                    for ( int i = mClients.size() - 1; i >= 0; i-- ) {
                        try {
                            mClients.get(i).send(Message.obtain(null, MSG_SET_VALUE, mValue, 0));
                        } catch (RemoteException e) {
                            mClients.remove(i);
                        }
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    final Messenger mMessenger = new Messenger(new IncomingHandler());

    @Override
    public void onCreate() {

        super.onCreate();
        //		LocalBroadcastManager.getInstance(this).registerReceiver(mPushMessageReceiver, new IntentFilter(PushMessageLocalBroadCast.INTENT_ACTION));
        //		util.setUserInfo(getApplicationContext());

        //startMemberPushTask();
        initGCM();

    }

    //	private PushMessageLocalBroadCast	mPushMessageReceiver	= new PushMessageLocalBroadCast() {
    //																	@Override
    //																	public void onMessage(String messageType, String msg, Boolean duplicate) {
    //
    //																		super.onMessage(messageType, msg, duplicate);
    //																		if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
    //																		} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
    //																		} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
    ////																			sendNotification(duplicate, msg);
    //
    //																		}
    //																	}
    //																};

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public void onRebind(Intent intent) {

        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        //LocalBroadcastManager.getInstance(this).unregisterReceiver(mPushMessageReceiver);
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public void onGCMRegistraterListener(int action, int resultCode, String message) {
        switch (action) {
            case GCMRegistrater.onGCMRegistraterListener.ACTION_SUCESS:
                sendGcmRegLocalBoradCast(action, resultCode, message);
                break;
            case GCMRegistrater.onGCMRegistraterListener.ACTION_NOT_PLAY_SERVICE:
            case GCMRegistrater.onGCMRegistraterListener.ACTION_DEVICE_NOT_SURPROT:
            case GCMRegistrater.onGCMRegistraterListener.ACTION_USE_PLAY_SERVICE:
            case GCMRegistrater.onGCMRegistraterListener.ACTION_REG_EXCEPTION:
            case GCMRegistrater.onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST:
                sendGcmRegLocalBoradCast(action, resultCode, message);
                // Pooling 시스템 구동 시작
                break;
            default:
                break;
        }

    }

    private void sendGcmRegLocalBoradCast(int action, int resultCode, String message) {
        Intent intent = new Intent(GcmRegLocalBroadCast.INTENT_ACTION);
        // add data
        intent.putExtra(GcmRegLocalBroadCast.INTENT_NAME_ACTION, action);
        intent.putExtra(GcmRegLocalBroadCast.INTENT_NAME_RESULT_CODE, resultCode);
        intent.putExtra(GcmRegLocalBroadCast.INTENT_NAME_MESSAGE, message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    //////////////////// Function ////////////////////

    /**
     * <pre>
     * GCM 초기화 등록
     * </pre>
     *
     * @return void
     * @author Sangtae
     * @since 2014. 4. 11. 오후 2:35:42
     */
    private void initGCM() {

        mGcmSharedPreferences = new GcmSharedPreferences(getApplicationContext());

        //		GCMRegistrater registrater1 = new GCMRegistrater(this, this);
        if ( mGcmSharedPreferences.getUnRegYN() == null ) {
            GCMRegistrater registrater = new GCMRegistrater(this, this);
        } else {
            if ( mGcmSharedPreferences.isRegistrationID() ) {        // GCM 등록 ID 존재 여부 확인
                sendGcmRegLocalBoradCast(GCMRegistrater.onGCMRegistraterListener.ACTION_SUCESS, GCMRegistrater.onGCMRegistraterListener.RESULT_CODE_NULL, mGcmSharedPreferences.getRegistrationID());
            } else {        // GCM 등록 ID 발급 시도
                GCMRegistrater registrater = new GCMRegistrater(this, this);
            }
        }
    }
}
