package com.example.weighttracker;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;

// This activity handles login and account creation.
public class MainActivity extends AppCompatActivity {

    private DatabaseHelper db;

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

        // Database helper handles user creation and login validation.
        db = new DatabaseHelper(this);

        // Login screen fields and buttons.
        TextInputEditText usernameInput = findViewById(R.id.usernameInput);
        TextInputEditText passwordInput = findViewById(R.id.passwordInput);

        Button loginButton = findViewById(R.id.loginButton);
        Button createAccountButton = findViewById(R.id.createAccountButton);

        // Existing users come through this path.
        loginButton.setOnClickListener(v -> {
            String username = InputHelper.getText(usernameInput);
            String password = InputHelper.getText(passwordInput);

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Enter username and password", Toast.LENGTH_SHORT).show();
                return;
            }

            if (db.validateUser(username, password)) {
                Toast.makeText(this, "Login success", Toast.LENGTH_SHORT).show();
                openWeightLog();
            } else {
                Toast.makeText(this, "Invalid login", Toast.LENGTH_SHORT).show();
            }
        });

        // New users can create an account from the same screen.
        createAccountButton.setOnClickListener(v -> {
            String username = InputHelper.getText(usernameInput);
            String password = InputHelper.getText(passwordInput);

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Enter username and password", Toast.LENGTH_SHORT).show();
                return;
            }

            if (db.userExists(username)) {
                Toast.makeText(this, "Username already exists", Toast.LENGTH_SHORT).show();
                return;
            }

            if (db.createUser(username, password)) {
                Toast.makeText(this, "Account created", Toast.LENGTH_SHORT).show();
                openWeightLog();
            } else {
                Toast.makeText(this, "Could not create account", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // I moved navigation into one method so login and account creation do not repeat it.
    private void openWeightLog() {
        startActivity(new Intent(this, WeightLogActivity.class));
        finish();
    }
}