package com.atmob.custom_notification;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.graphics.drawable.IconCompat;


import java.io.IOException;
import java.util.Objects;

public class NotificationUtil {

    private static final String TAG = "NotificationUtil";

    private static final String RECORD_DONE = "done";
    private static final String RECORD_RECORDING = "recording";
    private static final String RECORD_PAUSE = "pause";

    private static int NOTIFICATION_INTENT_REQUEST_CODE = 7777;
    public static final String KEY_RECORD_OPERATION = "key_record_operation";

    private static boolean isRecording;
    private static String timeDesc;

    private NotificationUtil() {

    }

    private static int getRequestCode() {
        return NOTIFICATION_INTENT_REQUEST_CODE++;
    }

    public static void showRecordNotification(@NonNull Context context, int notificationId, @NonNull String channelId, String channelName, String timeDesc, Boolean isRecording) {
        if(NotificationUtil.isRecording == isRecording && Objects.equals(NotificationUtil.timeDesc, timeDesc)) {
            return;
        }
        NotificationUtil.isRecording = isRecording;
        NotificationUtil.timeDesc = timeDesc;
//        Log.d(TAG, "showRecordNotification: isRecording: " + isRecording + " notificationId: " + notificationId + " timeDesc: " + timeDesc + " channelId: " + channelId + " channelName: " + channelName);
        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
        contentView.setImageViewResource(R.id.icon_notification_operation, isRecording ? R.drawable.icon_record_playing : R.drawable.icon_record_pause);
        contentView.setTextViewText(R.id.tv_title, isRecording ? "电子秘书 · 正在录音中" : "电子秘书 · 已暂停");
        contentView.setTextViewText(R.id.tv_record_time_desc, timeDesc);


        contentView.setOnClickPendingIntent(R.id.icon_notification_done, getActionIntent(context, RECORD_DONE));
        contentView.setOnClickPendingIntent(R.id.icon_notification_operation, getActionIntent(context, isRecording ? RECORD_PAUSE : RECORD_RECORDING));

        showNotification(context, contentView, notificationId, channelId, channelName, 3, true);
    }

    private static PendingIntent getActionIntent(Context context, String action) {
        Intent intent = getIntentToOpenMainActivity(context, action);
        return PendingIntent.getActivity(context, getRequestCode(),
                intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    }

    private static Intent getIntentToOpenMainActivity(Context context, String action) {
        final String packageName = context.getPackageName();
        return context
                .getPackageManager()
                .getLaunchIntentForPackage(packageName)
                .setAction(Intent.ACTION_VIEW)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .putExtra(KEY_RECORD_OPERATION, action);
    }


    private static void showNotification(@NonNull Context context, RemoteViews contentView, int notificationId, @NonNull String channelId, String channelName, int importance, boolean ongoing) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        if (!notificationManager.areNotificationsEnabled()) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId,
                    channelName, importance);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
        builder
                .setSmallIcon(R.drawable.logo)
                .setOngoing(ongoing)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setCustomContentView(contentView)
                .setCustomBigContentView(contentView)
                .setPriority(Notification.PRIORITY_HIGH);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
        }
        Notification notification = builder.build();

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
            notificationManager.notify(notificationId, notification);
        }
    }


    public static IconCompat getIconFromAsset(Context context, String imagePath) {
        if (imagePath != null) {
            AssetManager assetManager = context.getAssets();
            try (AssetFileDescriptor fd = assetManager.openFd(imagePath)) {
                Bitmap image = BitmapFactory.decodeStream(fd.createInputStream());
                return IconCompat.createWithBitmap(image);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String extraAction(Intent intent) {
        String action;
        if (intent != null && intent.getExtras() != null && (action = intent.getStringExtra(KEY_RECORD_OPERATION)) != null) {
            return action;
        }
        return null;
    }
}
