package it.integry.integrywmsnative.gest.login;

import android.os.Bundle;
import android.text.Html;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;

import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.SplashActivity;
import it.integry.integrywmsnative.core.di.BindableBoolean;
import it.integry.integrywmsnative.core.di.BindableString;
import it.integry.integrywmsnative.core.expansion.BaseActivity;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.UtilityWindow;
import it.integry.integrywmsnative.databinding.ActivityLoginBinding;
import it.integry.integrywmsnative.gest.login.viewmodel.LoginViewModel;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class LoginActivity extends BaseActivity implements LoginViewModel.Listener {

    ActivityLoginBinding mBindings;

    @Inject
    LoginViewModel mViewmodel;


    public BindableString username = new BindableString();
    public BindableString password = new BindableString();
    public BindableString codAzienda = new BindableString();

    public BindableBoolean customSettingsCheckboxEnabled = new BindableBoolean();
    public BindableBoolean customSettingsCheckboxChecked = new BindableBoolean();

    public BindableBoolean loginButtonEnabled = new BindableBoolean();


    public BindableString usernameError = new BindableString();
    public BindableString passwordError = new BindableString();
    public BindableString codAziendaError = new BindableString();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UtilityWindow.maximizeToFullScreen(this);

        mBindings = DataBindingUtil.setContentView(this, R.layout.activity_login);
        mBindings.setView(this);

        MainApplication.appComponent
                .loginActivityComponent()
                .create()
                .inject(this);

        mViewmodel.setListener(this);

        loginButtonEnabled.set(true);

        codAzienda.set(SettingsManager.i().getServer().getCodAzienda());

        customSettingsCheckboxChecked.set(SettingsManager.i().getServer().getHost() == null);
        customSettingsCheckboxEnabled.set(SettingsManager.i().getServer().getHost() != null);
    }


    public boolean validate(String username, String codAzienda) {
        if (username.isEmpty() || username.length() < 3) {
            usernameError.set(getText(R.string.username_error_not_valid).toString());
            return false;
        } else usernameError.set(null);

        if (codAzienda.isEmpty() || codAzienda.length() < 3) {
            codAziendaError.set(getText(R.string.server_cod_azienda_error_not_valid).toString());
            return false;
        } else codAziendaError.set(null);

        return true;
    }

    public void login() {
        if (validate(username.get(), codAzienda.get())) {
            loginButtonEnabled.set(false);
            mViewmodel.login(codAzienda.get(), username.get(), password.get());
        }
    }


    @Override
    public void onBackPressed() {
        // disable going back to the MainActivity
        moveTaskToBack(true);
    }

    @Override
    public void onLoginCompleted(String host, int port, String fullName, List<String> availableProfiles) {

        this.onLoadingEnded();
        runOnUiThread(() -> DialogSimpleMessageView.makeSuccessDialog(
                "Benvenuto",
                Html.fromHtml("Ciao <b>" + fullName + "</b>, la Integry le augura di svolgere al meglio il suo lavoro"),
                null,
                () -> showProfileDBSelectionDialog(host, port, availableProfiles))
                .show(getSupportFragmentManager(), "tag"));

    }


    @Override
    public void onError(Exception ex) {
        super.onError(ex);
        loginButtonEnabled.set(true);
    }

    private void showProfileDBSelectionDialog(final String host, final int port, final List<String> availableProfiles) {
        Runnable onComplete = () -> {
            SettingsManager.update();

            startSplashActivity();
        };

        loginButtonEnabled.set(true);

        if (availableProfiles != null && availableProfiles.size() == 1) {
            SettingsManager.i().getUserSession().setProfileDB(availableProfiles.get(0));

            mViewmodel.loadDepo(codAzienda.get(), host, port, username.get(), password.get(), onComplete);
        } else {

            // setup the alert builder
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.action_choose_profile_db);

            // add a list
            String[] profiles = new String[availableProfiles.size()];
            profiles = availableProfiles
                            .toArray(profiles);

            builder.setItems(profiles, (dialog, which) -> {
                SettingsManager.i().getUserSession().setProfileDB(availableProfiles.get(which));

                mViewmodel.loadDepo(codAzienda.get(), host, port, username.get(), password.get(), onComplete);
            });

            // create and show the alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

    private void startSplashActivity() {
        finish();
        SplashActivity.startActivity(this);
    }
}
