package com.miraclegarden.smsmessage.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.KeepAliveSettings;
import com.miraclegarden.smsmessage.R;
import com.miraclegarden.smsmessage.databinding.ActivityKeepAliveSettingsBinding;
import com.miraclegarden.smsmessage.service.MonitoredAppActivator;
import com.miraclegarden.smsmessage.service.MonitoredAppKeepAliveScheduler;
import com.miraclegarden.smsmessage.service.NotificationService;

import java.util.ArrayList;
import java.util.List;

public class KeepAliveSettingsActivity extends MiracleGardenActivity<ActivityKeepAliveSettingsBinding> {

    private boolean loadingUi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.ivBack.setOnClickListener(v -> finish());
        setupSpinners();
        loadFromPrefs();
        bindListeners();
    }

    private void setupSpinners() {
        binding.spinnerInterval.setAdapter(buildAdapter(formatIntervalOptions()));
        binding.spinnerCooldown.setAdapter(buildAdapter(formatCooldownOptions()));
    }

    private ArrayAdapter<String> buildAdapter(List<String> labels) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, labels);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        return adapter;
    }

    private List<String> formatIntervalOptions() {
        List<String> labels = new ArrayList<>();
        for (int minutes : KeepAliveSettings.INTERVAL_OPTIONS) {
            labels.add(minutes + " 分钟");
        }
        return labels;
    }

    private List<String> formatCooldownOptions() {
        List<String> labels = new ArrayList<>();
        for (int minutes : KeepAliveSettings.COOLDOWN_OPTIONS) {
            labels.add(minutes + " 分钟");
        }
        return labels;
    }

    private void loadFromPrefs() {
        loadingUi = true;
        binding.switchEnabled.setChecked(KeepAliveSettings.isEnabled(this));
        binding.switchStealthMode.setChecked(KeepAliveSettings.isStealthMode(this));
        binding.switchPreferRoot.setChecked(KeepAliveSettings.preferRoot(this));
        binding.switchReturnHome.setChecked(KeepAliveSettings.returnHome(this));
        binding.switchKillBeforeLaunch.setChecked(KeepAliveSettings.killBeforeLaunch(this));
        binding.spinnerInterval.setSelection(
                KeepAliveSettings.indexOfInterval(KeepAliveSettings.getIntervalMinutes(this)));
        binding.spinnerCooldown.setSelection(
                KeepAliveSettings.indexOfCooldown(KeepAliveSettings.getCooldownMinutes(this)));
        loadingUi = false;
        updateControlsEnabled();
    }

    private void bindListeners() {
        binding.switchEnabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (loadingUi) {
                return;
            }
            KeepAliveSettings.setEnabled(this, isChecked);
            updateControlsEnabled();
            applySchedule();
        });

        binding.switchStealthMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!loadingUi) {
                KeepAliveSettings.setStealthMode(this, isChecked);
            }
        });

        binding.switchPreferRoot.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!loadingUi) {
                KeepAliveSettings.setPreferRoot(this, isChecked);
            }
        });

        binding.switchReturnHome.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!loadingUi) {
                KeepAliveSettings.setReturnHome(this, isChecked);
            }
        });

        binding.switchKillBeforeLaunch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!loadingUi) {
                KeepAliveSettings.setKillBeforeLaunch(this, isChecked);
            }
        });

        binding.spinnerInterval.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (loadingUi) {
                    return;
                }
                KeepAliveSettings.setIntervalMinutes(
                        KeepAliveSettingsActivity.this, KeepAliveSettings.INTERVAL_OPTIONS[position]);
                applySchedule();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        binding.spinnerCooldown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!loadingUi) {
                    KeepAliveSettings.setCooldownMinutes(
                            KeepAliveSettingsActivity.this, KeepAliveSettings.COOLDOWN_OPTIONS[position]);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        binding.btnWakeNow.setOnClickListener(v -> {
            if (!KeepAliveSettings.isEnabled(this)) {
                Toast.makeText(this, R.string.keep_alive_wake_disabled, Toast.LENGTH_SHORT).show();
                return;
            }
            MonitoredAppActivator.activateAllAsync(this);
            Toast.makeText(this, R.string.keep_alive_wake_started, Toast.LENGTH_SHORT).show();
        });
    }

    private void applySchedule() {
        if (NotificationService.isMonitoringActive(this)) {
            if (KeepAliveSettings.isEnabled(this)) {
                MonitoredAppKeepAliveScheduler.schedule(this);
            } else {
                MonitoredAppKeepAliveScheduler.cancel(this);
            }
        }
    }

    private void updateControlsEnabled() {
        boolean enabled = binding.switchEnabled.isChecked();
        binding.spinnerInterval.setEnabled(enabled);
        binding.spinnerCooldown.setEnabled(enabled);
        binding.switchStealthMode.setEnabled(enabled);
        binding.switchPreferRoot.setEnabled(enabled);
        binding.switchKillBeforeLaunch.setEnabled(enabled);
        binding.switchReturnHome.setEnabled(enabled);
        binding.btnWakeNow.setEnabled(enabled);
    }
}
