package com.haussteuerung;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

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

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    String url = "";

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d("Firebase", remoteMessage.getFrom() + ", " + remoteMessage.getData().get("content"));

        // Wenn eine Activity geöffnet ist oder die FB-Nachricht nicht "Es hat gel" enthält, eine Toastbox zeigen, ansonsten eine Notification senden
        if (AppLifecycleTracker.isAppInForeground()) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> Toast.makeText(getApplicationContext(), remoteMessage.getData().get("content"), Toast.LENGTH_LONG).show());
        } else {
            if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel")) {
                url = "https://www.klebl.info/cam/" + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43) + ".jpg";
                deleteImageFromMediaStore(getApplicationContext(), "cam.jpg");
                downloadImageToGallery(getApplicationContext(), url, "cam.jpg");
                downloadImageToGallery(getApplicationContext(), url, Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43) + ".jpg");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.d("onMessageReceived - Firebase", "1sec timer failed");
                }

                sendNotification(remoteMessage);
                Log.d("Notification", "Glocke");
            } else {
                sendNotification(remoteMessage);
                Log.d("Notification", "Everything else");
            }
        }
    }

    public void downloadImageToGallery(Context context, String imageUrl, String filename) {
        new Thread(() -> {
            try {
                InputStream inputStream = new URL(imageUrl).openStream();

                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

                Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                if (uri != null) {
                    OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        Objects.requireNonNull(outputStream).write(buffer, 0, bytesRead);
                    }
                    Objects.requireNonNull(outputStream).close();
                    inputStream.close();
                }
            } catch (Exception e) {
                Log.d("downloadImageToGallery - Firebase", "Downloading camera picture failed");
            }
        }).start();
    }

    public void deleteImageFromMediaStore(Context context, String filename) {
        Uri collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Images.Media.DISPLAY_NAME + "=?";
        String[] selectionArgs = new String[]{filename};

        context.getContentResolver().delete(collection, selection, selectionArgs);
    }

    public void sendNotification(RemoteMessage remoteMessage) {
        String content;
        PendingIntent pendingIntent = null;

        Map<String, String> data = remoteMessage.getData();
        String title = data.get("title");
        if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel")) {
            content = "Es hat um "
                    + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(37, 39) + ":"
                    + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(39, 41) + ":"
                    + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(41, 43) + " geläutet, Tür öffnen!";
        } else {
            content = data.get("content");
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID;

        // Entscheiden, welche Activity mit welchen Extras gestartet werden soll
        if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel")) {
            NOTIFICATION_CHANNEL_ID = "Glocke";

            Intent intent1 = new Intent(this, MainActivity.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent1.putExtra("Glocke", "Glocke");
            intent1.putExtra("Time", Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43));
            Log.d("GlockeFirebase", Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                intent1.setIdentifier(Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43));
            }
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, PendingIntent.FLAG_IMMUTABLE);

        } else if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Waschmaschine")) {
            NOTIFICATION_CHANNEL_ID = "Waschmaschine";
        } else {
            NOTIFICATION_CHANNEL_ID = "Sonstiges";

            Intent intent4 = new Intent(this, MainActivity.class);
            intent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent4.putExtra("Other", remoteMessage.getData().get("content"));
            Log.d("OtherFirebase", Objects.requireNonNull(remoteMessage.getData().get("content")));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                intent4.setIdentifier(remoteMessage.getData().get("content"));
            }
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent4, PendingIntent.FLAG_IMMUTABLE);
        }

        String description = "Haussteuerung - " + NOTIFICATION_CHANNEL_ID;

        NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, description, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription(description);
        channel.setShowBadge(true);
        channel.canShowBadge();
        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});

        notificationManager.createNotificationChannel(channel);

        Random notification_id = new Random();

        Bitmap bitmap = null;
        try {
            InputStream in = new URL(url).openStream();
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (Exception e) {
            Log.d("sendNotification - Firebase", "Loading bitmap cam.jpg from MediaStore failed");
        }

        NotificationCompat.Builder notificationBuilder;
        if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel")) {
            notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setContentIntent(pendingIntent)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.haus_icon))
                    .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap))
                    .setSmallIcon(R.drawable.haus_icon);
        } else {
            notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setContentIntent(pendingIntent)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.haus_icon))
                    .setSmallIcon(R.drawable.haus_icon);
        }
        Log.d("num", String.valueOf(notification_id.nextInt(1000)));

        notificationManager.notify(notification_id.nextInt(1000), notificationBuilder.build());
    }
}
