package kr.co.compcarecompany.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 android.os.VibrationEffect;
import android.os.Vibrator;

import androidx.core.app.NotificationCompat;

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

import static android.content.Context.VIBRATOR_SERVICE;
import static kr.co.compcarecompany.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, cp_idx;

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

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

    public String get_alarmThread_title() {
        return message;
    }

    public String get_alarmThread_cpIdx() {
        return cp_idx;
    }

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

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

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

    private void sendNotification(String title, String message, String send_type) {

        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 soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getApplicationContext().getPackageName() + "/" + R.raw.alarm_01);
        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 =
                    new Notification.Builder(context.getApplicationContext(), "alarm_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 notificationChannel = new NotificationChannel("alarm_channel", "기계 상태이상 알림", NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setVibrationPattern(vibratePattern);
            notificationChannel.enableVibration(true);


            // Configure the notification channel.
            AudioAttributes att = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();

            notificationChannel.setSound(soundUri, att);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.YELLOW);
            notify_manager.createNotificationChannel(notificationChannel);
            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(soundUri)
                            .setVibrate(vibratePattern)
                            .setStyle(new NotificationCompat.BigTextStyle().bigText("알람을 끄려면 알림현황에서 해제를 누르세요."))
                            .setContentIntent(pendingIntent);

            notify_manager.notify(0 /* ID of notification */, notificationBuilder.build());
        }
    }
}
