package kr.co.compcareworker.Util.Service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Handler;

import androidx.core.app.NotificationCompat;

import kr.co.compcareworker.Activity.Intro;
import kr.co.compcareworker.R;

import static kr.co.compcareworker.MyApplication.notify_manager;

public class AlarmThread extends Thread {
    private Handler handler;
    private boolean isRun = true;
    private static int SLEEP = 5000;
    private Context context;
    String title, message;


    public AlarmThread(Context context, String title, String message) {
        this.context = context;
        this.title = title;
        this.message = message;
    }

    public void stopForever() {
        synchronized (this) {
            this.isRun = false;
        }
    }

    public void run() {
        //반복적으로 수행할 작업을 한다.
        while (isRun) {
            sendNotification(title, message);

            if (Thread.interrupted()) {
                break;
            }

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

    private void sendNotification(String title, String message) {

        Intent intent = new Intent(context, Intro.class);
        intent.setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        Uri warning_soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getApplicationContext().getPackageName() + "/" + R.raw.warning_alarm);
        Uri service_soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getApplicationContext().getPackageName() + "/" + R.raw.service_alarm);

        final long[] vibratePattern = new long[]{0, 300, 0, 300, 0, 300, 0, 300, 0, 300, 0, 300, 0, 300, 0};

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Notification.Builder notificationBuilder;
            NotificationChannel notificationChannel;
            // Configure the notification channel.
            AudioAttributes att = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();

            if (message.contains("주의")) {

                notificationBuilder =
                        new Notification.Builder(context.getApplicationContext(), "warning_channel")
                                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher))
                                .setSmallIcon(R.mipmap.launcher)
                                .setContentTitle(title)
                                //.setContentText("알람을 끄려면 알림현황에서 해제를 누르세요.")
                                .setAutoCancel(true)
                                .setStyle(new Notification.BigTextStyle().bigText("알람을 끄려면 알림현황에서 해제를 누르세요."))
                                .setContentIntent(pendingIntent);

                notificationChannel = new NotificationChannel("warning_channel", "기계 상태이상 알림", NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setSound(warning_soundUri, att);

            } else {

                notificationBuilder =
                        new Notification.Builder(context.getApplicationContext(), "service_channel")
                                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher))
                                .setSmallIcon(R.mipmap.launcher)
                                .setContentTitle(title)
                                //.setContentText("알람을 끄려면 알림현황에서 해제를 누르세요.")
                                .setAutoCancel(true)
                                .setStyle(new Notification.BigTextStyle().bigText("알람을 끄려면 알림현황에서 해제를 누르세요."))
                                .setContentIntent(pendingIntent);

                notificationChannel = new NotificationChannel("service_channel", "기계 상태이상 알림", NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setSound(service_soundUri, att);
            }

            notificationChannel.setVibrationPattern(vibratePattern);
            notificationChannel.enableVibration(true);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.YELLOW);
            notify_manager.createNotificationChannel(notificationChannel);
            notify_manager.notify(0 /* ID of notification */, notificationBuilder.build());

        } else {

            if (message.contains("주의")) {

                NotificationCompat.Builder notificationBuilder =
                        new NotificationCompat.Builder(context.getApplicationContext())
                                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher))
                                .setSmallIcon(R.mipmap.launcher)
                                .setContentTitle(title)
                                //.setContentText("알람을 끄려면 알림현황에서 해제를 누르세요.")
                                .setAutoCancel(true)
                                .setSound(warning_soundUri)
                                .setVibrate(vibratePattern)
                                .setStyle(new NotificationCompat.BigTextStyle().bigText("알람을 끄려면 알림현황에서 해제를 누르세요."))
                                .setContentIntent(pendingIntent);
                notify_manager.notify(0 /* ID of notification */, notificationBuilder.build());

            } else {
                NotificationCompat.Builder notificationBuilder =
                        new NotificationCompat.Builder(context.getApplicationContext())
                                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher))
                                .setSmallIcon(R.mipmap.launcher)
                                .setContentTitle(title)
                                //.setContentText("알람을 끄려면 알림현황에서 해제를 누르세요.")
                                .setAutoCancel(true)
                                .setSound(service_soundUri)
                                .setVibrate(vibratePattern)
                                .setStyle(new NotificationCompat.BigTextStyle().bigText("알람을 끄려면 알림현황에서 해제를 누르세요."))
                                .setContentIntent(pendingIntent);
                notify_manager.notify(0 /* ID of notification */, notificationBuilder.build());

            }

        }
    }
}
