/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ntels.onecable.common.gcm;

import com.google.android.gms.gcm.GcmListenerService;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.db.DatabaseOpenHelper;
import com.ntels.onecable.common.db.SqlManager;
import com.ntels.onecable.common.db.entity.TblLoginInfo;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.view.Intro;
import com.ntels.onecable.view.dialog.PushDialog;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.util.List;

/**
 * GcmIntentService
 * 
 *
 */
public class GcmIntentService extends GcmListenerService {

	private static final String TAG = "GcmIntentService";
	private Boolean isPushSound;
    private Boolean isPushVibration;
    
    private AudioManager mAudioManager;

    Boolean bDialog = false;
    Util util = new Util();
	
//    public GcmIntentService()
//    {
//        super(Constants.GCM_SENDER_ID);
//    }

//    @Override
//    protected void onRegistered(Context context, String registrationId)
//    {
//        DLog.i( "Device registered: regId = " + registrationId);
//        PrefUtils.setString(context, PrefConstants.GCM_ID, registrationId);
//
////        Intent intent = new Intent();
////        intent.setAction("com.ntels.POCT.REGIST_GCM_ID");
////        context.sendBroadcast(intent);
//
//
//        GCMRegistrar.onDestroy(context);
//    }
//
//    @Override
//    protected void onUnregistered(Context context, String registrationId) {
//    	DLog.i( "Device unregistered");
//    	PrefUtils.setString(context, PrefConstants.GCM_ID, "none");
//    }



    /**
     * @param from SenderID 값을 받아온다.
     * @param data Set형태로 GCM으로 받은 데이터 payload이다.
     */
    @Override
    public void onMessageReceived(String from, Bundle data) {
    	Dlog.i( "GCM Received Org message=" + data.toString());

        Intent intent = new Intent();
        intent.putExtras(data);
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) { // has effect of unparcelling Bundle
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString(), "", "", "");
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString(), "", "", "");
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                String msg = util.null2string(intent.getStringExtra("msg"));
                String push_method = util.null2string(intent.getStringExtra("push_method"));
                String push_type_code = util.null2string(intent.getStringExtra("push_noti_type_code"));
                String button_name = util.null2string(intent.getStringExtra("button_name"));
                String homegrp_id = util.null2string(intent.getStringExtra("homegrp_id"));
                if (push_method.equals("01")) {
                    bDialog = false;
                } else {
                    bDialog = true;
                }
                sendNotification(msg, push_type_code, button_name, homegrp_id);
                Dlog.i("GcmIntentService1.java | onHandleIntent", "Received: " + extras.toString());
            }
        }
//        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    /**
     * Send push notification.
     *
     * @param msg            Push message
     * @param push_type_code Push type code(ex> HOME_MEM_SEL...)
     * @param button_name    Button name
     * @param homegrp_id     Member home group id
     */
    private void sendNotification(String msg, String push_type_code, String button_name, String homegrp_id) {

        int iDialogType = 0;
        Boolean bPush = false;
        String sMsg = "";
        SqlManager sqlManager = new SqlManager();
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(getApplicationContext()).getWritableDatabase();
        Cursor cursor = db.rawQuery(sqlManager.qryLoginInfo(), null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            if (util.null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.PUSH_YN))).equals("N")) {
                bPush = false;
            } else {
                bPush = true;
            }
            cursor.moveToNext();
        }
        cursor.close();
        db.close();
        if (bPush) {
            sMsg = msg;
            NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

            Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            notificationIntent.setData(Uri.parse(util.getPreferences(this, Constants.EXTRA_APPSTART_ID) + "://start?type=" + push_type_code));
            PendingIntent launchIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            String contentTitle = util.getString(this, R.string.app_name);
            String contentText = sMsg;

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setSmallIcon(R.drawable.notification_icon);
            Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            mBuilder.setLargeIcon(bm);
            mBuilder.setContentTitle(contentTitle);
            mBuilder.setAutoCancel(true);
            mBuilder.setVibrate(new long[]{1000});
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(contentText);
            mBuilder.setContentIntent(launchIntent);

//            if ( iDialogType < 2 ) {
            mNotificationManager.notify(Constants.NOTIFICATION_ID, mBuilder.build());
//            } else {
//                mNotificationManager.cancel(Constants.NOTIFICATION_ID);
//                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//                v.vibrate(1000);
//            }

            int iBadgeCnt = util.null2int(util.getPreferences(getApplicationContext(), "badge_count"));
            iBadgeCnt++;
            util.setPreferences(getApplicationContext(), "badge_count", iBadgeCnt + "");
            Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
            // 패키지 네임과 클래스 네임 설정
            intent.putExtra("badge_count_package_name", getPackageName());
            intent.putExtra("badge_count_class_name", Intro.class.getCanonicalName());
            // 업데이트 카운트
            intent.putExtra("badge_count", iBadgeCnt);
            sendBroadcast(intent);

            //			PushWakeLock.acquireCpuWakeLock(mContext);
            if (bDialog) {
                Intent i = new Intent(this, PushDialog.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                i.putExtra(Constants.EXTRA_BODY, sMsg);
//                i.putExtra(Constants.EXTRA_CALL_TYPE, iDialogType);
                i.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, push_type_code);
                i.putExtra(Constants.EXTRA_BUTTON_NAME, button_name);
                i.putExtra(Constants.EXTRA_HOMEGRP_ID, homegrp_id);
                String sAppProc = "STOP";
                //실행여부
                if (isAppRunning()) {
                    //백그라운드 여부
                    if (isAppIsInBackground()) {
                        sAppProc = "BACKGROUND";
                    } else {
                        sAppProc = "FOREGROUND";
                    }
                } else {
                    sAppProc = "STOP";
                }
                i.putExtra(Constants.EXTRA_APP_PROC, sAppProc);

                startActivity(i);
            }
        }
    }

    /**
     * App이 백그라운드에서 실행중인지 확인.
     *
     * @return 백그라운드 실행여부
     */
    private boolean isAppIsInBackground() {

        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * App이 실행중인지 확인.
     *
     * @return 실행 여부
     */
    public boolean isAppRunning() {
        boolean isAppRunning = false;
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(100);

            String pageName = "com.example.packagename";
            pageName = getPackageName();
            for (ActivityManager.RunningTaskInfo info : list) {
                if (info.topActivity.getPackageName().equals(pageName) || info.baseActivity.getPackageName().equals(pageName)) {
                    isAppRunning = true;
                    Log.i("SystemUtils", info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isAppRunning;
    }



}
