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

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

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 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 java.util.ArrayList;

/**
 * <pre>
 * 1. ClassName :   PushService
 * 2. FileName  :   PushService.java
 * 3. Package   :   com.ntels.kneet.v3.common.gcm.service
 * 4. Date      :   2016-12-05
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class PushService extends Service implements GcmRegister.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();
        initGCM();

    }

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

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

    }

    /**
     * GCM 등록 결과 브로드캐스팅.
     *
     * @param action     {@link GcmRegLocalBroadCast#INTENT_ACTION}
     * @param resultCode {@link GcmRegLocalBroadCast#INTENT_NAME_RESULT_CODE}
     * @param message    {@link GcmRegLocalBroadCast#INTENT_NAME_MESSAGE}
     */
    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 ////////////////////

    /**
     * GCM 초기화 등록
     */
    private void initGCM() {

        mGcmSharedPreferences = new GcmSharedPreferences(getApplicationContext());

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