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

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

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

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

import android.app.ActivityManager;
import android.app.IntentService;
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.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;

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

    Boolean bDialog = false;
    Util util = new Util();

    public GcmIntentService() {

        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        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("GcmIntentService.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(context);
            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;
    }

}
