package kr.co.compcareworker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.NotificationManager;
import android.content.Context;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.kakao.sdk.common.KakaoSdk;
import com.kakao.vectormap.KakaoMapSdk;
import com.kakao.vectormap.LatLng;


import java.util.ArrayList;

import kr.co.compcareworker.Util.MonitoringThread;
import kr.co.compcareworker.Util.Service.AlarmThread;
import kr.co.compcareworker.Util.ServiceThread;
import kr.co.compcareworker.Util.TerminateThread;

public class MyApplication extends Application {
    public static Context context;
    public static boolean isBackground = false;
    public static LatLng lastMapPoint = null;
    public static boolean uploadFinish = true;
    public static boolean uploadError = false;
    public static boolean stop_ui_change = false;
    public static boolean finishMonitoring = false;
    @SuppressLint("StaticFieldLeak")
    public static Activity myActivity;
    private TerminateThread thread;
    public static ArrayList<ServiceThread> serviceThreads = new ArrayList<>();
    public static ArrayList<MonitoringThread> monitoringThread = new ArrayList<>();
    private LifecycleObserver lifecycleObserver = new CycleListener();
    public static NotificationManager notify_manager;
    public static AlarmThread alarm_thread;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        // Kakao SDK 초기화
        KakaoSdk.init(this, getString(R.string.kakao_key));
        KakaoMapSdk.init(this, getString(R.string.kakao_key));
        setupLifecycleObserver();
    }

    private void setupLifecycleObserver() {
        ProcessLifecycleOwner.get().getLifecycle().addObserver(lifecycleObserver);
        notify_manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    class CycleListener implements LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onMoveToFoground() {
            isBackground = false;
            if (thread != null) {
//                Log.d("끝냈어용@@@@", "ㅇㅇㅇㅇ");
                thread.interrupt();
                thread = null;
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onMoveToBackground() {
//            Log.d("시작이용@@@@", "ㅇㅇㅇㅇ");
            isBackground = true;
            if (thread == null) {
                thread = new TerminateThread();
                thread.start();
            }
        }
    }
}
