package co.pixelbeard.theanfieldwrap.signUp.name;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.rw.keyboardlistener.KeyboardUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.customView.PBInputField;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.signUp.SignUpFragmentListener;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.DialogUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import co.pixelbeard.theanfieldwrap.utils.ValidationUtils;
import io.realm.Realm;

public class SignUpNameFragment extends BaseFragment implements SignUpNameContract.View {

    private static final String TAG = SignUpNameFragment.class.getSimpleName();

    @BindView(R.id.pb_first_name)
    PBInputField pbFirstName;
    @BindView(R.id.pb_last_name)
    PBInputField pbLastName;
    @BindView(R.id.pb_user_name)
    PBInputField pbUserName;

    @BindView(R.id.txt_already_got_account)
    TextView txtAlreadyGotAccount;

    private boolean userNameAvailable;

    private SignUpFragmentListener mListener;
    private Context mContext;

    private SignUpNameContract.Presenter mPresenter;

    public SignUpNameFragment() {
        // Required empty public constructor
    }

    public static SignUpNameFragment newInstance() {
        SignUpNameFragment fragment = new SignUpNameFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mListener = (SignUpFragmentListener) context;
        this.mContext = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }

        new SignUpNamePresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sign_up_name, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

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

        setInputFieldFont();
        setInputFieldImeListener();
        setInputFieldTextWatcher();

        txtAlreadyGotAccount.setTypeface(FontUtils.getInstance().getDinAlternateBold());

        mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), false);
    }

    @Override
    public void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);
    }

    private void setInputFieldFont() {
        pbFirstName.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
        pbFirstName.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbFirstName.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbFirstName.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());

        pbLastName.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
        pbLastName.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbLastName.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbLastName.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());

        pbUserName.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
        pbUserName.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbUserName.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbUserName.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setInputFieldImeListener() {
        pbFirstName.setImeActionListener((v, actionId, event) -> {
            pbLastName.requestTheFocus();
            return true;
        });

        pbLastName.setImeActionListener((v, actionId, event) -> {
            pbUserName.requestTheFocus();
            return true;
        });

        pbUserName.setImeActionListener((v, actionId, event) -> {
            KeyboardUtils.forceCloseKeyboard(pbUserName);
            return true;
        });
    }

    private void setInputFieldTextWatcher() {
        pbFirstName.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                pbFirstName.resetError();
                mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pbLastName.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                pbLastName.resetError();
                mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pbUserName.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                pbUserName.resetError();
                mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), false);
                if (ValidationUtils.isValidUsername(pbUserName.getText())) {
                    mPresenter.checkUserNameAvailable(pbUserName.getText());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void isValidated() {

        boolean validated = true;

        if (!mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), true) || !userNameAvailable) {
            validated = false;
        }

        if (validated && mListener != null) {
            mListener.setSignUpEmailPasswordFrag();
            mListener.setFirstName(pbFirstName.getText());
            mListener.setLastName(pbLastName.getText());
            mListener.setUserName(pbUserName.getText());
        }
    }

    @Override
    public void showFirstNameError() {
        if (pbFirstName != null && isAdded()) {
            pbFirstName.showError(getString(R.string.first_name_error));
        }
    }

    @Override
    public void showLastNameError() {
        if (pbLastName != null && isAdded()) {
            pbLastName.showError(getString(R.string.last_name_error));
        }
    }

    @Override
    public void showInvalidUserNameError() {
        if (pbUserName != null && isAdded()) {
            pbUserName.showError(getString(R.string.user_name_error));
        }
    }

    @Override
    public void showUserNameNotAvailableError() {
        if (pbUserName != null && isAdded()) {
            pbUserName.showError(getString(R.string.user_name_unavailable));
        }

    }

    @Override
    public void enableButton() {
        if (userNameAvailable && mListener != null) {
            mListener.enableButton();
        }
    }

    @Override
    public void disableButton() {
        if (mListener != null && isAdded()) {
            mListener.disableButton();
        }
    }

    @Override
    public void setUserNameAvailable(boolean isAvailable) {
        this.userNameAvailable = isAvailable;
        if (isAvailable && mPresenter.validateFields(pbFirstName.getText(), pbLastName.getText(), pbUserName.getText(), false)) {
            enableButton();
        } else disableButton();
    }

    @Override
    public void showNoConnectionHeader() {
        if (mListener != null && isAdded()) {
            mListener.showNoInternetHeader();
        }
    }

    @Override
    public void setPresenter(SignUpNameContract.Presenter presenter) {
        if (presenter != null) {
            this.mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        //Not needed
    }

    @Override
    public void showLoader(String text) {
        //Not needed
    }

    @Override
    public void hideLoader() {
        //Not needed
    }

    @Override
    public void onUnknownError(String error) {
        if (isAdded()) {
            showSingleButtonDialog(getString(R.string.error), error, null);
        }
    }

    private void showSingleButtonDialog(String string, String error, DialogInterface.OnDismissListener listener) {
        if (isAdded()) {
            DialogUtils.showSingleButtonDialog(string, error, mContext, listener);
        }
    }

    @Override
    public void onTimeout() {
        if (isAdded()) {
            showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body), null);
        }
    }

    @Override
    public void onNetworkError() {
        if (isAdded()) {
            showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body), null);
        }
    }

    @Override
    public void onConnectionError() {
        if (mListener != null && isAdded()) {
            mListener.showNoInternetHeader();
        }
    }

    @Override
    public void logoutUser() {
        //Not needed
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(mContext);
    }
}
