package org.torproject.artitoyvpn.ui.settings;

import android.app.Application;
import android.widget.Toast;

import androidx.lifecycle.AndroidViewModel;

import org.torproject.artitoyvpn.R;
import org.torproject.artitoyvpn.utils.PreferenceHelper;
import org.torproject.onionmasq.OnionMasq;
import org.torproject.onionmasq.errors.CountryCodeException;

public class SettingsViewModel extends AndroidViewModel {

    private final PreferenceHelper preferenceHelper;


    public SettingsViewModel(Application application) {
        super(application);
        preferenceHelper = new PreferenceHelper(application);
    }

    public String getBridgeLines() {
        return preferenceHelper.getBridgeLines();
    }

    public void onBridgeLinesChanged(String lines) {
        if (lines.isBlank()) {
            preferenceHelper.setBridgeLines(null);
        } else {
            preferenceHelper.setBridgeLines(lines);
        }
    }

    public int getExitNodeCountryPos() {
        String cc = preferenceHelper.getExitNodeCountry();
        String[] countries = getApplication().getResources().getStringArray(R.array.countries);
        for (int i = 0; i < countries.length; i++) {
            if (countries[i].equals(cc)) {
                return i;
            }
        }
        return 0;
    }

    public
    void onCountryCodeSelected(int pos) {
        String[] countries = getApplication().getResources().getStringArray(R.array.countries);
        String country = countries[pos];
        if (country.equals("(any)")) {
            country = null;
        }
        try {
            OnionMasq.setCountryCode(country);
            preferenceHelper.setExitNodeCountry(country);
        } catch (CountryCodeException e) {
            throw new RuntimeException(e);
        }
    }

    public void resetCountryCode() {
        Toast.makeText(getApplication(), "Unsetting country.", Toast.LENGTH_SHORT).show();
        try {
            OnionMasq.setCountryCode(null);
            preferenceHelper.setExitNodeCountry(null);
        } catch (CountryCodeException e) {
            throw new RuntimeException(e);
        }
    }
}