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

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

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.util.Dlog;

import android.content.Context;
import android.os.AsyncTask;

import java.io.IOException;

/**
 * <pre>
 * 1. ClassName :   GcmRegister
 * 2. FileName  :   GcmRegister.java
 * 3. Package   :   com.ntels.kneet.v3.common.gcm.service
 * 4. Date      :   2016-12-05
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class GcmRegister {

    private Context mContext;

    private AsyncTask<Void, Void, String> mAsyncTask;
    private GoogleCloudMessaging mGCM;
    private String mRegistrationID;
    private Boolean mGCMService;

    private onGCMRegistraterListener mGcmRegistraterListener;
    private GcmSharedPreferences mGcmSharedPreferences;

    /**
     * 생성자.
     *
     * @param context                컨텍스트
     * @param gcmRegistraterListener GCM 등록 결과 리스너
     */
    public GcmRegister(Context context, onGCMRegistraterListener gcmRegistraterListener) {
        mContext = context;
        mGcmRegistraterListener = gcmRegistraterListener;
        mGCMService = checkPlayServices();

        mGcmSharedPreferences = new GcmSharedPreferences(mContext);

        if (mGCMService) {
            createAsyncTask();
            registerInBackground();
        }
    }

    /**
     * GCM 서비스 체크.
     *
     * @return 체크 결과
     */
    private boolean checkPlayServices() {

        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {        // 사용자 대응 가능 오류
                //GooglePlayServicesUtil.getErrorDialog(resultCode, this, onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST).show();
                mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST, resultCode, GooglePlayServicesUtil.getErrorString(resultCode));
            } else {
                mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.ACTION_DEVICE_NOT_SURPROT, resultCode, GooglePlayServicesUtil.getErrorString(resultCode));
            }
            mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.ACTION_NOT_PLAY_SERVICE, resultCode, GooglePlayServicesUtil.getErrorString(resultCode));
            return false;
        }

        mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.ACTION_USE_PLAY_SERVICE, resultCode, "");
        return true;
    }

    /**
     * GCM Client ID 등록 요청 스레드 시작.
     */
    private void registerInBackground() {
        if (mAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
            createAsyncTask();
            mAsyncTask.execute(null, null, null);
        } else if (mAsyncTask.getStatus() == AsyncTask.Status.PENDING) {
            mAsyncTask.execute(null, null, null);
        }
    }

    /**
     * GCM Client ID 등록 요청 스레드 오브젝트 생성.
     */
    private void createAsyncTask() {
        mAsyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (mGCM == null) {
                        mGCM = GoogleCloudMessaging.getInstance(mContext.getApplicationContext());
                    }
                    if (mGcmSharedPreferences.getUnRegYN() == null) {
                        mGCM.unregister();
                        mGcmSharedPreferences.setUnRegYN("Y");
                    }
                    mRegistrationID = mGCM.register(AppConfig.getInstance().getProject_Id());
                    msg = "Device registered, registration ID=" + mRegistrationID;
                    mGcmSharedPreferences.setRegistrationID(mRegistrationID);
                    mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.ACTION_SUCESS, onGCMRegistraterListener.RESULT_CODE_NULL, mRegistrationID);
                } catch (IOException ex) {

                    mGcmRegistraterListener.onGCMRegistraterListener(onGCMRegistraterListener.ACTION_REG_EXCEPTION, onGCMRegistraterListener.RESULT_CODE_NULL, ex.getMessage());
                    msg = "Error :" + ex.getMessage();
                }

                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                Dlog.i("MainActivity.java | onPostExecute", "|" + msg + "|");
                //_textStatus.append(msg);
            }
        };
    }

    /////////////////////////////////////// onGCMRegistraterListener	///////////////////////////////////////

    /**
     * GcmRegister 작업 수행 리스너.
     */
    public interface onGCMRegistraterListener {

        /**
         * 등록 성공.
         */
        public final int ACTION_SUCESS = 40000;

        /**
         * 구글 플레이서비스 미활성화.
         */
        public final int ACTION_NOT_PLAY_SERVICE = 40001;

        /**
         * 구글 플레이서비스 하드웨어 미지원.
         */
        public final int ACTION_DEVICE_NOT_SURPROT = 40002;

        /**
         * 구글 플레이 서비스 활성화.
         */
        public final int ACTION_USE_PLAY_SERVICE = 40003;

        /**
         * 플레이 서비스 작업 요청 중 에러.
         */
        public final int ACTION_REG_EXCEPTION = 40004;

        /**
         * <pre>
         * GCM 사용자 대응 가능 오류.
         * <ol>GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
         * onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST).show()  사용하여, 사용자 대응 가능</ol>
         * </pre>
         */
        public final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

        /**
         * ResultCode 무효값.
         */
        public final int RESULT_CODE_NULL = -1;

        /**
         * GCM ID 작업 요청.
         *
         * @param action     발생 상황
         * @param resultCode 상태 코드
         * @param message    상태 메시지
         */
        void onGCMRegistraterListener(int action, int resultCode, String message);
    }
}
