/*
 * 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.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

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.Notification;
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.support.v4.app.NotificationCompat;
import android.util.Log;

import java.util.List;
import java.util.Map;

/**
 * FcmIntentService.
 * 
 *
 */
public class FcmIntentService extends FirebaseMessagingService {

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

    Boolean bDialog = false;
    String mPushMethod = "";
    Util mUtil = new Util();
	
//    public FcmIntentService()
//    {
//        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(RemoteMessage message) {

        Map<String, String> data = message.getData();
    	Dlog.i("FCM Received Org message=" + data.toString());

//        Intent intent = new Intent();
//        intent.putExtra(message.getData());
//        Bundle extras = intent.getExtras();
//        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
//        String messageType = gcm.getMessageType(intent);

        if (!data.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 = mUtil.null2string(intent.getStringExtra("msg"));
                String push_method = mUtil.null2string(intent.getStringExtra("push_method"));
                String push_type_code = mUtil.null2string(intent.getStringExtra("push_noti_type_code"));
                String button_name = mUtil.null2string(intent.getStringExtra("button_name"));
                String homegrp_id = mUtil.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());
            }
        }
//        FcmBroadcastReceiver.completeWakefulIntent(intent);
    }*/

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Map<String, String> data = remoteMessage.getData();
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            String msg = mUtil.null2string(data.get("msg"));
            // 푸쉬가 보여지는 형태 (01 : head up, 02 : popup, 03 : notification)
            mPushMethod = mUtil.null2string(data.get("push_method"));
            String pushNotiTypeCode = mUtil.null2string(data.get("push_noti_type_code"));
            String buttonName = mUtil.null2string(data.get("button_name"));
            String homegrpId = mUtil.null2string(data.get("homegrp_id"));
            if ("01".equals(mPushMethod) || "03".equals(mPushMethod)) {
                bDialog = false;
            } else {
                bDialog = true;
            }
            sendNotification(msg, pushNotiTypeCode, buttonName, homegrpId);
            Dlog.i("FcmIntentService1.java | onHandleIntent", "Received: " + data.toString());

            /*if (*//* Check if data needs to be processed by long running job *//* true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }*/

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]

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

        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 (mUtil.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(mUtil.getPreferences(this, Constants.EXTRA_APPSTART_ID) + "://start?type=" + pushTypeCode));
            PendingIntent launchIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            String contentTitle = mUtil.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));

            if ("01".equals(mPushMethod)) {
                mBuilder.setWhen(System.currentTimeMillis());
                mBuilder.setPriority(Notification.PRIORITY_MAX);
                mBuilder.setContentText(contentText);
                launchIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                mBuilder.setFullScreenIntent(launchIntent, true);
                if ("MAS_GRD_ACCEPT".equals(pushTypeCode) || "MAS_GRD_REJECT".equals(pushTypeCode)) {
                    bDialog = true;
                }
            } else {
                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 = mUtil.null2int(mUtil.getPreferences(getApplicationContext(), "badge_count"));
            iBadgeCnt++;
            mUtil.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, pushTypeCode);
                i.putExtra(Constants.EXTRA_BUTTON_NAME, buttonName);
                i.putExtra(Constants.EXTRA_HOMEGRP_ID, homegrpId);
                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;
    }



}
