package com.amazon.ads.apidemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.amazon.ads.apidemo.utils.L;

public class MainService extends Service {
    private static Intent sStartIntent;
    private static MainService sInstance;

    private final Handler mHandler = new Handler();

    public static void start(Context ctx) {
        sStartIntent = new Intent(ctx, MainService.class);
        try {
            ctx.startForegroundService(sStartIntent);
        } catch (Throwable e) {
            L.w("Start Misc service failed:" + e);
        }
    }

    public static void stop(Context ctx) {
        if (sInstance != null && sStartIntent != null) {
            try {
                ctx.stopService(sStartIntent);
            } catch (Throwable e) {
                L.w("Stop Misc service failed:" + e);
            }
            sInstance = null;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        L.i("AdminService hashCode:" + hashCode());
        sInstance = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        L.w("onStartCommand action: " + intent.getAction());
        L.w("onStartCommand flags: " + flags);
        L.w("onStartCommand startId: " + startId);

        mHandler.postDelayed(mCheckRunnable, 1000);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        L.w("onDestroy");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        L.w("onBind action: " + intent.getAction());
        return null;
    }


    private final Runnable mCheckRunnable = new Runnable() {
        @Override
        public void run() {
            // L.i("MyActivity.isForeground:", MyActivity.isForeground);

            mHandler.postDelayed(mCheckRunnable, 1000);
        }
    };


}
