package info.knacki.prometheusandroidexporter;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.view.View;
import android.widget.QuickContactBadge;
import android.widget.TextView;

import java.util.List;
import java.util.logging.Logger;

public class MainActivity extends AppCompatActivity {
    private final static Logger log = Logger.getLogger(MainActivity.class.getName());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.bt_killservice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainService.StopService(MainActivity.this);
                UpdateUiState();
            }
        });
        findViewById(R.id.bt_startservice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainService.StartService(MainActivity.this);
                UpdateUiState();
            }
        });
        UpdateUiState();
    }

    private boolean IsServiceRunning() {
        final ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
        final String serviceClassName = MainService.class.getName();

        for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName))
                return true;
        }
        return false;
    }

    private void UpdateUiState() {
        boolean running = IsServiceRunning();
        findViewById(R.id.bt_killservice).setEnabled(running);
        findViewById(R.id.bt_startservice).setEnabled(!running);
        ((TextView) findViewById(R.id.txt_servicestate)).setText(running ? "running" : "stopped");
    }
}
