package kr.co.hanwha.hifive.fcm;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

import kr.co.hanwha.hifive.BuildConfig;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.screen.common.LandingActivity;
import kr.co.hanwha.hifive.util.HFNotiUtil;

/**
 * Created by sanghoonkwon on 2018. 2. 9..
 */

public class HFFirebaseMessagingService extends FirebaseMessagingService {
    private final String TAG = getClass().getSimpleName();

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
//        super.onMessageReceived(remoteMessage);
        // ...

        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        if (BuildConfig.DEBUG) Log.d(TAG, "From: " + remoteMessage.getFrom());

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

            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();
            }

            String title = "";
            String message = "";
            String group_id = "";
            String type = "";
            String value1 = "";
            String value2 = "";
            String value3 = "";
            String db_code = "";
            Map<String, String> datas = remoteMessage.getData();
            if (datas != null) {
                if (datas.containsKey(HFNotiUtil.KEY_TITLE))
                    title = datas.get(HFNotiUtil.KEY_TITLE);
                if (datas.containsKey(HFNotiUtil.KEY_BODY))
                    message = datas.get(HFNotiUtil.KEY_BODY);
                if (datas.containsKey(HFNotiUtil.KEY_GROUP_ID))
                    group_id = datas.get(HFNotiUtil.KEY_GROUP_ID);
                if (datas.containsKey(HFNotiUtil.KEY_TYPE))
                    type = datas.get(HFNotiUtil.KEY_TYPE);
                if (datas.containsKey(HFNotiUtil.KEY_VALUE1))
                    value1 = datas.get(HFNotiUtil.KEY_VALUE1);
                if (datas.containsKey(HFNotiUtil.KEY_VALUE2))
                    value2 = datas.get(HFNotiUtil.KEY_VALUE2);
                if (datas.containsKey(HFNotiUtil.KEY_VALUE3))
                    value3 = datas.get(HFNotiUtil.KEY_VALUE3);
                if (datas.containsKey(HFNotiUtil.KEY_DB_CODE)) {
                    db_code = datas.get(HFNotiUtil.KEY_DB_CODE);
                }
            }

            makeNotification(group_id, title, message, type, value1, value2, value3, db_code);
        }

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

            String title = remoteMessage.getNotification().getTitle();
            String message = remoteMessage.getNotification().getBody();
            String group_id = "";
            String type = "";
            String value1 = "";
            String value2 = "";
            String value3 = "";
            Map<String, String> datas = remoteMessage.getData();
            if (datas != null && datas.containsKey(HFNotiUtil.KEY_GROUP_ID))
                group_id = datas.get(HFNotiUtil.KEY_GROUP_ID);
            if (datas != null && datas.containsKey(HFNotiUtil.KEY_TYPE))
                type = datas.get(HFNotiUtil.KEY_TYPE);
            if (datas != null && datas.containsKey(HFNotiUtil.KEY_VALUE1))
                value1 = datas.get(HFNotiUtil.KEY_VALUE1);
            if (datas != null && datas.containsKey(HFNotiUtil.KEY_VALUE2))
                value2 = datas.get(HFNotiUtil.KEY_VALUE2);
            if (datas != null && datas.containsKey(HFNotiUtil.KEY_VALUE3))
                value3 = datas.get(HFNotiUtil.KEY_VALUE3);

            makeNotification(group_id, title, message, type, value1, value2, value3);
        }
        */

        // 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.
    }

    private void makeNotification(String group_id, String title, String message, String type, String value1, String value2, String value3, String db_code) {
        try {
            Intent intent = new Intent(getApplicationContext(), LandingActivity.class);
            if (TextUtils.isEmpty(group_id) == false)
                intent.putExtra(HFNotiUtil.KEY_GROUP_ID, group_id);
            if (TextUtils.isEmpty(type) == false) intent.putExtra(HFNotiUtil.KEY_TYPE, type);
            if (TextUtils.isEmpty(value1) == false)
                intent.putExtra(HFNotiUtil.KEY_VALUE1, value1);
            if (TextUtils.isEmpty(value2) == false)
                intent.putExtra(HFNotiUtil.KEY_VALUE2, value2);
            if (TextUtils.isEmpty(value3) == false)
                intent.putExtra(HFNotiUtil.KEY_VALUE3, value3);
            if (TextUtils.isEmpty(db_code) == false)
                intent.putExtra(HFNotiUtil.KEY_DB_CODE, db_code);

//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // Create the NotificationChannel
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "Notification", importance);
                channel.setDescription("Notification");
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{100, 200, 100, 200});
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.createNotificationChannel(channel);

                Notification.Builder builder = new Notification.Builder(getApplicationContext(), "CHANNEL_ID")
                        .setContentTitle(title)
                        .setContentText(message)
                        .setTicker(message)
                        .setSmallIcon(R.mipmap.noti_icon)
                        .setAutoCancel(true)
                        .setContentIntent(pendingIntent);

                notificationManager.notify((int) System.currentTimeMillis(), builder.build());// TODO - CHECK Noti ID
            } else {
//                NotificationCompat.Builder builder= new NotificationCompat.Builder(this);
                Notification.Builder builder = new Notification.Builder(this);
                builder.setSmallIcon(R.mipmap.noti_icon);    // required
                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.launcher_icon));
                builder.setContentTitle(title);                // required
                builder.setContentText(message);               // required
//                builder.setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle());
                builder.setTicker(message);                    // optional
                builder.setAutoCancel(true);
                builder.setContentIntent(pendingIntent);

                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify((int) System.currentTimeMillis(), builder.build());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
