package com.cygnusa.hyperm.pushnotification;

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.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Handler;
import android.os.Message;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.NotificationActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.SplashScreen;
import com.cygnusa.hyperm.util.DatabaseHelper;

import org.jetbrains.annotations.NotNull;

import java.util.Map;

public class FcmMessageService extends FirebaseMessagingService {

    SQLiteDatabase sdb;
    SharedPreferences preferences;

    @Override
    public void onMessageReceived(@NotNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Map<String, String> data = remoteMessage.getData();
        try {
            sdb = new DatabaseHelper(getBaseContext(), "hyperm.db", null, 2).getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cursor cursor = sdb.rawQuery("select * from session", null);
        if (cursor.getCount() > 0) {
            try {
                sendNotification(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onNewToken(@NotNull String s) {
        super.onNewToken(s);
    }

    Handler handler = new Handler(msg -> {
        if (msg.arg1 == 1) {
            try {
                new Handler(HomeActivity.notificationCallback).sendEmptyMessage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                new Handler(NotificationActivity.notificationCallback).sendEmptyMessage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    });

    private void sendNotification(Map<String, String> data) {
        preferences = getSharedPreferences("MySettings",
                Context.MODE_PRIVATE);

        Message msg = new Message();
        msg.arg1 = 1;
        handler.sendMessage(msg);

        String message = data.get("message");
        String title = data.get("title");

        Intent intent = new Intent(this, SplashScreen.class);
        intent.putExtra("canGoNotification", true);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel-01");
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setChannelId("channel-01");
        notificationBuilder.setContentText(message);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setContentIntent(pendingIntent);
        notificationBuilder.setContentInfo("");
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle()
                .bigText(message));
        notificationBuilder.setContentText(message);
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        notificationBuilder.setColor(Color.parseColor("#2f6aac"));
        notificationBuilder.setLights(Color.RED, 1000, 300);

        if (preferences.getBoolean("sound", true)) {
            notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        } else if (preferences.getBoolean("vibrate", true)) {
            notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            notificationBuilder.setSound(null);
        }
        if (!preferences.getBoolean("vibrate", true) && !preferences.getBoolean("sound", true)) {
            notificationBuilder.setSound(null);
        } else if (preferences.getBoolean("vibrate", true) && preferences.getBoolean("sound", true)) {
            notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        }

        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);

        int lo = (int) (System.currentTimeMillis() % 1000);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(SplashScreen.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(lo,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notificationBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);

        assert mNotificationManager != null;
        String channelId = "channel-01";
        String channelName = "HYPER-M";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(mChannel);
        }

        mNotificationManager.notify(lo, notificationBuilder.build());
    }
}