package ru.myitschool.work.ui.login;

import android.util.Base64;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.navigation.Navigation;

import java.nio.charset.StandardCharsets;

import ru.myitschool.work.R;
import ru.myitschool.work.data.repository.LoginRepositoryImpl;
import ru.myitschool.work.domain.login.AuthUseCase;

public class LoginViewModel extends ViewModel {

    private final MutableLiveData<Boolean> mutableButtonStateLiveData = new MutableLiveData<>();
    public final LiveData<Boolean> buttonStateLiveData = mutableButtonStateLiveData;

    private final MutableLiveData<String> mutableLoginStateLiveData = new MutableLiveData<>();
    public final LiveData<String> loginStateLiveData = mutableLoginStateLiveData;


    private final AuthUseCase authUseCase = new AuthUseCase(LoginRepositoryImpl.getInstance());


    private String login = "";
    private String password = "";

    public void onChangeLogin(String login) {
        this.login = login;
        onChangeButtonState(login, this.password);
        Log.d("TAG", login);
        Log.d("TAG", password);
    }
    public void onChangePassword(String password) {
        this.password = password;
        onChangeButtonState(this.login, password);
        Log.d("TAG", login);
        Log.d("TAG", password);
    }

    private void onChangeButtonState(String login, String password) {
        if (login.length() >= 3 && !Character.isDigit(login.charAt(0)) && login.matches("^[a-zA-Z0-9]*$") && password.length() >= 3) {
            mutableButtonStateLiveData.postValue(true);
        } else {
            mutableButtonStateLiveData.postValue(false);
        }
    }

    public void startQuery() {
        final String currentLogin = login, currentPassword = password;
        authUseCase.execute("Basic " + Base64.encodeToString((currentLogin + ":" + currentPassword).getBytes(StandardCharsets.UTF_8), Base64.DEFAULT), status -> {
            if (status.getStatusCode() == 200) {
                mutableLoginStateLiveData.postValue("Correct Login");
            } else /*(status.getStatusCode() == 401) */ {
                mutableLoginStateLiveData.postValue("Incorrect Login");
            }
            Log.d("TAG", String.valueOf(status.getStatusCode()));
        });
        Log.d("TAG", login);
        Log.d("TAG", password);
        Log.d("TAG", "Basic " + Base64.encodeToString((currentLogin + ":" + currentPassword).getBytes(StandardCharsets.UTF_8), Base64.DEFAULT));

    }
}
