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

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

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;

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 java.io.IOException;
/**
 * <pre>
 * GCM 크라이언트 등록 클래스
 * </pre>
 * <p/>
 * 등록 완료 후 이후 메시지나 관련 에러는 브로드캐스트로 전달됨.
 *
 * @author Sangtae
 * @since 2014. 3. 8. 오후 3:41:16
 */
public class GCMRegistrater {

    private Context mContext;

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

    private onGCMRegistraterListener mGcmRegistraterListener;
    private GcmSharedPreferences     mGcmSharedPreferences;

    public GCMRegistrater(Context context, onGCMRegistraterListener gcmRegistraterListener) {
        mContext = context;
        mGcmRegistraterListener = gcmRegistraterListener;
        mGCMService = checkPlayServices();

        mGcmSharedPreferences = new GcmSharedPreferences(mContext);

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

    /**
     * <pre>
     * GCM 서비스 체크
     * </pre>
     *
     * @return boolean
     * @author Sangtae
     * @since 2014. 3. 7. 오전 11:47:30
     */
    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;
    }

    /**
     * <pre>
     * 어플 버전명 반환
     * </pre>
     *
     * @return String
     * @author Sangtae
     * @since 2014. 3. 7. 오전 11:37:36
     */
    private String getAppVersion() {
        try {
            PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    /**
     * <pre>
     * GCM Client ID 등록 요청 스레드 시작
     * </pre>
     *
     * @return void
     * @author Sangtae
     * @since 2014. 3. 7. 오후 2:27:23
     */
    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);
        }
    }

    /**
     * <pre>
     * GCM Client ID 등록 요청 스레드 오브젝트 생성
     * </pre>
     *
     * @return void
     * @author Sangtae
     * @since 2014. 3. 7. 오후 2:28:14
     */
    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	///////////////////////////////////////

    /**
     * <pre>
     * GCMRegistrater 작업 수행 리스너
     * </pre>
     *
     * @author Sangtae
     * @since 2014. 3. 8. 오후 6:11:29
     */
    public interface onGCMRegistraterListener {

        /**
         * <pre>
         * 등록 성공
         * </pre>
         */
        public final int ACTION_SUCESS             = 40000;
        /**
         * <pre>
         * 구글 플레이서비스 미활성화
         * </pre>
         */
        public final int ACTION_NOT_PLAY_SERVICE   = 40001;
        /**
         * <pre>
         * 구글 플레이서비스 하드웨어 미지원
         * </pre>
         */
        public final int ACTION_DEVICE_NOT_SURPROT = 40002;
        /**
         * <pre>
         * 구글 플레이 서비스 활성화
         * </pre>
         */
        public final int ACTION_USE_PLAY_SERVICE   = 40003;
        /**
         * <pre>
         * 플레이 서비스 작업 요청 중 에러
         * </pre>
         */
        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;

        /**
         * <pre>
         * ResultCode 무효값
         * </pre>
         */
        public final int RESULT_CODE_NULL = -1;

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