package co.pixelbeard.theanfieldwrap.signUp.auth;


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 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 io.realm.Realm;

public class SignUpAuthCodeFragment extends BaseFragment implements SignUpAuthCodeContract.View {

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


    @BindView(R.id.pb_auth_code)
    PBInputField pbAuthCode;

    private static final String USER_EMAIL = "USER_EMAIL";
    private static final String USER_PASSWORD = "USER_PASSWORD";
    private static final String FROM_LOGIN = "FROM_LOGIN";
    private String mUserEmail, mUserPassword;
    private boolean mFromLogin;

    private SignUpFragmentListener mListener;
    private Context mContext;

    private SignUpAuthCodeContract.Presenter mPresenter;

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

    public static SignUpAuthCodeFragment newInstance(String userEmail, String userPassword, boolean fromLogin) {
        SignUpAuthCodeFragment fragment = new SignUpAuthCodeFragment();
        Bundle args = new Bundle();
        args.putString(USER_EMAIL, userEmail);
        args.putString(USER_PASSWORD, userPassword);
        args.putBoolean(FROM_LOGIN, fromLogin);
        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) {
            mUserEmail = getArguments().getString(USER_EMAIL);
            mUserPassword = getArguments().getString(USER_PASSWORD);
            mFromLogin = getArguments().getBoolean(FROM_LOGIN);
        }

        new SignUpAuthCodePresenter(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_auth_code, 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();
    }

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

    private void setInputFieldFont() {
        pbAuthCode.setInputType(InputType.TYPE_CLASS_TEXT);
        pbAuthCode.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbAuthCode.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbAuthCode.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setInputFieldImeListener() {
        pbAuthCode.setImeActionListener((v, actionId, event) -> {
            KeyboardUtils.forceCloseKeyboard(pbAuthCode);
            return true;
        });
    }

    private void setInputFieldTextWatcher() {
        pbAuthCode.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) {
                pbAuthCode.resetError();
                mPresenter.validateField(pbAuthCode.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void isValidated() {
        boolean validated = true;

        if (!mPresenter.validateField(pbAuthCode.getText(), true)) {
            validated = false;
        }

        if (validated) {
            mPresenter.activateUser(mUserEmail, mUserPassword, pbAuthCode.getText(), mFromLogin, mListener.isFromGuest());
        }

    }

    @Override
    public void showInvalidAuthCodeError() {
        if (pbAuthCode != null && isAdded()) {
            pbAuthCode.showError(getString(R.string.invalid_auth_code));
        }
    }

    @Override
    public void showIncorrectAuthCodeError() {
        if (pbAuthCode != null && isAdded()) {
            pbAuthCode.showError(getString(R.string.incorrect_auth_code));
        }

    }

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

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

    @Override
    public void setPresenter(SignUpAuthCodeContract.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) {
        if (mListener != null && isAdded()) {
            mListener.showLoader(text);
        }
    }

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

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

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

    @Override
    public void onNetworkError() {
        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 void showSingleButtonDialog(String title, String body, DialogInterface.OnDismissListener listener) {
        if (isAdded()) {
            DialogUtils.showSingleButtonDialog(title, body, mContext, listener);
        }
    }

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

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

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

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

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