package com.dragonssh.xhttpdemo;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.dragonssh.xhttpdemo.core.config.Settings;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputLayout;

public final class SettingsActivity extends AppCompatActivity {
    private Settings settings;
    private EditText serverField;
    private EditText portField;
    private EditText usernameField;
    private EditText passwordField;
    private EditText sniField;
    private EditText xhttpHostField;
    private EditText pathField;
    private SwitchMaterial xhttpTlsSwitch;
    private TextInputLayout passwordLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        WindowInsetsHelper.apply(this, R.id.settings_root);

        settings = new Settings(this);
        bindViews();
        loadConfiguration();

        findViewById(R.id.back).setOnClickListener(v -> finish());
        findViewById(R.id.save_settings).setOnClickListener(v -> saveConfiguration());
    }

    private void bindViews() {
        serverField = findViewById(R.id.server);
        portField = findViewById(R.id.port);
        usernameField = findViewById(R.id.username);
        passwordField = findViewById(R.id.password);
        sniField = findViewById(R.id.sni);
        xhttpHostField = findViewById(R.id.xhttp_host);
        pathField = findViewById(R.id.xhttp_path);
        xhttpTlsSwitch = findViewById(R.id.xhttp_tls);
        passwordLayout = findViewById(R.id.password_layout);
    }

    private void loadConfiguration() {
        serverField.setText(settings.getPrivString(Settings.XHTTP_ENDPOINT_KEY));
        portField.setText(settings.getPrivString(Settings.XHTTP_PORT_KEY));
        usernameField.setText(settings.getPrivString(Settings.USUARIO_KEY));
        sniField.setText(settings.getPrivString(Settings.CUSTOM_SNI));
        xhttpHostField.setText(settings.getPrivString(Settings.XHTTP_HOST_KEY));
        pathField.setText(settings.getPrivString(Settings.XHTTP_PATH_KEY));
        xhttpTlsSwitch.setChecked(!"0".equals(settings.getPrivString(Settings.XHTTP_TLS_KEY)));

        DemoApplication application = (DemoApplication) getApplication();
        passwordField.setText(application.getSessionPassword());
        passwordLayout.setHelperText(application.hasSessionPassword()
                ? getString(R.string.password_loaded_for_session)
                : getString(R.string.password_storage_notice));
    }

    private void saveConfiguration() {
        String server = text(serverField);
        String port = text(portField);
        String username = text(usernameField);
        String password = rawText(passwordField);
        String path = ConfigUtils.normalizePath(text(pathField));

        if (server.isEmpty()) {
            showError(R.string.error_server_required);
            serverField.requestFocus();
            return;
        }
        if (!ConfigUtils.isValidPort(port)) {
            showError(R.string.error_port_invalid);
            portField.requestFocus();
            return;
        }
        if (username.isEmpty()) {
            showError(R.string.error_username_required);
            usernameField.requestFocus();
            return;
        }

        DemoApplication application = (DemoApplication) getApplication();
        if (password.isEmpty()) {
            showError(R.string.error_password_required);
            passwordField.requestFocus();
            return;
        }
        if (path.isEmpty()) {
            showError(R.string.error_path_required);
            pathField.requestFocus();
            return;
        }

        SharedPreferences.Editor editor = settings.getPrefsPrivate().edit();
        editor.putString(Settings.XHTTP_ENDPOINT_KEY, server)
                .putString(Settings.XHTTP_PORT_KEY, port)
                .putString(Settings.USUARIO_KEY, username)
                .putString(Settings.PORTA_LOCAL_KEY, "1080")
                .putString(Settings.CUSTOM_SNI, text(sniField))
                .putString(Settings.XHTTP_HOST_KEY, text(xhttpHostField))
                .putString(Settings.XHTTP_PATH_KEY, path)
                .putString(Settings.XHTTP_TLS_KEY, xhttpTlsSwitch.isChecked() ? "1" : "0")
                .apply();

        application.setSessionPassword(password);

        setResult(RESULT_OK);
        Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_SHORT).show();
        finish();
    }

    private void showError(int messageRes) {
        Toast.makeText(this, messageRes, Toast.LENGTH_LONG).show();
    }

    private static String text(EditText view) {
        return view.getText() == null ? "" : view.getText().toString().trim();
    }

    private static String rawText(EditText view) {
        return view.getText() == null ? "" : view.getText().toString();
    }
}
