package co.pixelbeard.theanfieldwrap.editEmail;


import android.content.Context;
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.LinearLayout;
import android.widget.TextView;

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

import com.rw.keyboardlistener.KeyboardUtils;

import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
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.home.HomeFragmentListener;
import co.pixelbeard.theanfieldwrap.playerService.MediaPlayerInterface;
import co.pixelbeard.theanfieldwrap.playerService.PodcastStorageUtil;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import io.realm.Realm;

public class EditEmailFragment extends BaseFragment implements EditEmailContract.View {

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

    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.txt_edit_email_title)
    TextView txtEditEmailTitle;

    @BindView(R.id.btn_save)
    CircularProgressButton btnSave;

    @BindView(R.id.pb_edit_email)
    PBInputField pbEditEmail;

    private HomeFragmentListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;
    private Context mContext;
    private EditEmailContract.Presenter mPresenter;
    private boolean emailAvailable = false;

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

    public static EditEmailFragment newInstance() {
        EditEmailFragment fragment = new EditEmailFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

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

        mListener = (HomeFragmentListener) context;
        mediaPlayerInterface = (MediaPlayerInterface) context;
        mContext = context;
    }

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

        new EditEmailPresenter(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_edit_email, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

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


        setButtonFont();
        setButtonClickListener();

        setTextViewFont();

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


        pbEditEmail.setText(PrefUtils.getInstance().getStringPref(PrefKey.EMAIL));

    }

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

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        btnSave.dispose();

        mPresenter.unsubscribe();
    }

    private void setButtonFont() {
        btnSave.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setButtonClickListener() {
        btnSave.setOnClickListener(v -> {
            if (mPresenter.checkForChanges(pbEditEmail.getText())) {
                if (mPresenter.validateEmail(pbEditEmail.getText(), true) && emailAvailable) {
                    mPresenter.updateEmail(pbEditEmail.getText());
                }
            } else {
                goBack();
            }
        });

        llBack.setOnClickListener(v -> goBack());
    }

    private void setTextViewFont() {
        txtEditEmailTitle.setTypeface(FontUtils.getInstance().getDinProBlack());
    }

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

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

    private void setInputFieldTextWatcher() {

        pbEditEmail.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) {
                pbEditEmail.resetError();

                if (mPresenter.checkForChanges(s.toString())) {
                    if (mPresenter.validateEmail(s.toString(), false)) {
                        mPresenter.checkEmailAvailable(s.toString());
                    }
                } else {
                    disableButton();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    @Override
    public void showEmailError(String message) {
        if (pbEditEmail != null && isAdded()) {
            pbEditEmail.showError(message);
        }
    }

    @Override
    public void showInvalidEmailError() {
        if (pbEditEmail != null && isAdded()) {
            pbEditEmail.showError(getString(R.string.invalid_email));
        }
    }

    @Override
    public void enableButton() {
        if (btnSave != null && isAdded() && emailAvailable) {
            btnSave.setAlpha(1.0f);
        }
    }

    @Override
    public void disableButton() {
        if (btnSave != null && isAdded()) {
            btnSave.setAlpha(0.2f);
        }
    }

    @Override
    public void showEmailNotAvailableError() {
        if (pbEditEmail != null && isAdded()) {
            pbEditEmail.showError(getString(R.string.email_in_use));
        }
    }

    @Override
    public void setEmailAvailable(boolean isEmailAvailable) {
        this.emailAvailable = isEmailAvailable;

        if (isEmailAvailable && mPresenter.checkForChanges(pbEditEmail.getText())) {
            if (mPresenter.validateEmail(pbEditEmail.getText(), false)) {
                enableButton();
            } else disableButton();
        }

    }

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

    @Override
    public void goBack() {
        if (mListener != null) {
            mListener.goBack();
        }
    }

    @Override
    public void showLoader(String text) {
        if (btnSave != null && isAdded()) {
            btnSave.startMorphAnimation();
        }
    }

    @Override
    public void hideLoader() {
        if (btnSave != null && isAdded()) {
            btnSave.revertAnimation(() -> null);
        }
    }

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

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

    @Override
    public void onNetworkError() {
        if (mListener != null && isAdded()) {
            mListener.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() {
        mPresenter.clearUserData(mContext);
        if (mediaPlayerInterface.isPlaying()) {
            mediaPlayerInterface.stop();
        }
        PodcastStorageUtil.getInstance().clearStoredPodcast();
        mListener.startWalkThroughActivity();
    }

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