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.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

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

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(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 (((!MainActivity.pausedMainActivity)
                || (!activityDoris.pausedDoris)
                || (!activityDorisLicht.pausedDorisLicht)
                || (!activityGlocke.pausedGlocke)
                || (!activityHaus.pausedHaus)
                || (!activityLicht.pausedLicht)
                || (!activityLog.pausedLog)
                || (!activitySky.pausedSky)
                || (!activityLWP.pausedLWP))
                && (!Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel"))) {
            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")) {
                downloadFile(remoteMessage);

                try {
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

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


    public void downloadFile(RemoteMessage remoteMessage) {
        File fileCam = new File(Environment.getExternalStorageDirectory().getPath() + "/Pictures/Haussteuerung/");
        if (!fileCam.exists()) {
            fileCam.mkdir();
        }

        if (Objects.requireNonNull(remoteMessage.getData().get("content")).contains("Es hat gel")) {
            Log.d("Foto", remoteMessage.getData().get("content"));
            String url = "https://www.klebl.info/cam/" + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43) + ".jpg";
            Log.d("Foto", url);

            String f1 = Environment.getExternalStorageDirectory().getPath() + "/Pictures/Haussteuerung/" + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43) + ".jpg";
            String f2 = Environment.getExternalStorageDirectory().getPath() + "/Pictures/Haussteuerung/cam.jpg";
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Thread gfgThread = new Thread(() -> {
                    try {
                        InputStream in = null;
                        try {
                            in = new URL(url).openStream();
                            Log.d("Foto", "Verbindung zum Server erfolgreich. Download wird durchgeführt.");
                        } catch (IOException e) {
                            // Wenn kein Foto gemacht wurde, hat das Foto 0kb, daher 404 error.
                            Log.d("Foto", "Verbindungsfehler. Foto am Server prüfen.");
                        }
                        try {
                            Files.copy(in, Paths.get(f1), StandardCopyOption.REPLACE_EXISTING);
                            Log.d("Foto", "Foto 1 Download");
                            Thread.sleep(200);
                            Files.copy(Paths.get(f1), Paths.get(f2), StandardCopyOption.REPLACE_EXISTING);
                            Log.d("Foto", "Foto 2 Download");
                            Log.d("Foto", "Download und Speichern erfolgreich.");
                        } catch (IOException e) {
                            Log.d("Foto", "Download fehlgeschlagen.");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                gfgThread.start();

                // MediaScanner starten um das Foto in die Gallery zu bringen
                MediaScannerConnection.scanFile(getApplicationContext(), new String[]{f1},
                        new String[]{"image/jpg"}, null);
                MediaScannerConnection.scanFile(getApplicationContext(), new String[]{f2},
                        new String[]{"image/jpg"}, null);
            });
        }
    }

    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);
            Log.d("GlockeFirebase", Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43));
            // intent1.putExtra("Glocke", "Glocke");
            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));
            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 /* Request code */, intent1, PendingIntent.FLAG_IMMUTABLE);

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

            Intent intent2 = new Intent(this, MainActivity.class);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent2.putExtra("Sky", "Sky");
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent2, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

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

            Intent intent3 = new Intent(this, FileDownload.class);
            intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent3, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        } 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"));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                intent4.setIdentifier(remoteMessage.getData().get("content"));
            }
            Log.d("OtherFirebase", Objects.requireNonNull(remoteMessage.getData().get("content")));
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0 /* Request code */, 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.setLightColor(getResources().getColor(R.color.gradient_blue));
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});

        notificationManager.createNotificationChannel(channel);

        Random notification_id = new Random();

        NotificationCompat.Builder notificationBuilder = null;
        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))
                    .setLights(getResources().getColor(R.color.gradient_blue), 1000, 300)
                    .setStyle(new NotificationCompat.BigPictureStyle()
                            .bigPicture(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + "/Pictures/Haussteuerung/" + Objects.requireNonNull(remoteMessage.getData().get("content")).substring(28, 43) + ".jpg")))
                    .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))
                    .setLights(getResources().getColor(R.color.gradient_blue), 1000, 300)
                    .setSmallIcon(R.drawable.haus_icon);
        }

        Log.d("num", String.valueOf(notification_id.nextInt(1000)));

        assert notificationManager != null;
        notificationManager.notify(notification_id.nextInt(1000), notificationBuilder.build());
    }
}
