package org.mercury_im.messenger.android.ui.account.login;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;

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

import org.mercury_im.messenger.android.MercuryImApplication;
import org.mercury_im.messenger.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AddAccountDialogFragment extends AppCompatDialogFragment {

    @BindView(R.id.username)
    TextInputEditText addressView;

    @BindView(R.id.username_layout)
    TextInputLayout addressLayout;

    @BindView(R.id.password)
    TextInputEditText passwordView;

    @BindView(R.id.password_layout)
    TextInputLayout passwordLayout;

    private AndroidLoginViewModel viewModel;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_login, null);
        ButterKnife.bind(this, dialogView);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(R.string.action_add_account)
                .setView(dialogView)
                .setCancelable(false)
                .setPositiveButton(R.string.action_sign_in, null)
                .setNegativeButton(R.string.button_cancel, cancelButtonClickListener);

        return builder.create();
    }

    private final DialogInterface.OnClickListener cancelButtonClickListener =
            (dialog, which) -> AddAccountDialogFragment.this.onCancel(dialog);

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        final AlertDialog d = (AlertDialog)getDialog();
        if(d == null) {
            return;
        }

        viewModel = new AndroidLoginViewModel(MercuryImApplication.getApplication());

        Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(v -> viewModel.onLoginButtonClicked());

        viewModel.getLoginUsernameError().observe(this, error -> addressLayout.setError(error));
        viewModel.getLoginPasswordError().observe(this, error -> passwordLayout.setError(error));
        viewModel.isLoginButtonEnabled().observe(this, positiveButton::setEnabled);

        viewModel.isLoginFinished().observe(this, finished -> {
            if (finished) {
                dismiss();
            }
        });

        addressView.addTextChangedListener(viewModel.getUsernameTextChangedListener());
        passwordView.addTextChangedListener(viewModel.getPasswordTextChangedListener());

        addressView.setOnEditorActionListener(focusPasswordFieldOnEnterPressed);
        passwordView.setOnEditorActionListener(loginOnEnterPressed);
    }

    private final TextView.OnEditorActionListener focusPasswordFieldOnEnterPressed = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                passwordView.requestFocus();
                return true;
            }
            return false;
        }
    };

    private final TextView.OnEditorActionListener loginOnEnterPressed = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_NULL) {
                viewModel.getCommonViewModel().login();
                return true;
            }
            return false;
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
