package org.torproject.artitoyvpn.ui.settings;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;

import org.torproject.artitoyvpn.R;
import org.torproject.artitoyvpn.databinding.FragmentSettingsBinding;

public class SettingsFragment extends Fragment {

    private SettingsViewModel settingsViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        settingsViewModel =
                new ViewModelProvider(this).get(SettingsViewModel.class);

        FragmentSettingsBinding binding = FragmentSettingsBinding.inflate(inflater, container, false);

        Spinner countrySpinner = binding.countrySpinner;
        countrySpinner.setSelection(settingsViewModel.getExitNodeCountryPos());
        countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                settingsViewModel.onCountryCodeSelected(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                settingsViewModel.resetCountryCode();
            }
        });

        binding.editBridgeLine.setText(settingsViewModel.getBridgeLines());
        binding.editBridgeLine.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                settingsViewModel.onBridgeLinesChanged(s.toString());
            }
        });

        binding.textAppList.setOnClickListener(v -> NavHostFragment.findNavController(SettingsFragment.this).navigate(R.id.action_navigation_settings_to_navigation_apps));

        return binding.getRoot();
    }

}