package co.pixelbeard.theanfieldwrap.editPassword;


import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
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.TawController;
import io.realm.Realm;

public class EditPasswordFragment extends BaseFragment implements EditPasswordContract.View {

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

    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.txt_edit_password_title)
    TextView txtEditPasswordTitle;

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

    @BindView(R.id.pb_current_password)
    PBInputField pbCurrentPassword;
    @BindView(R.id.pb_new_password)
    PBInputField pbNewPassword;
    @BindView(R.id.pb_confirm_new_password)
    PBInputField pbConfirmNewPassword;

    private HomeFragmentListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;
    private Context mContext;

    private EditPasswordContract.Presenter mPresenter;

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

    public static EditPasswordFragment newInstance() {
        EditPasswordFragment fragment = new EditPasswordFragment();
        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 EditPasswordPresenter(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_password, 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();

        mPresenter.validateFields(pbCurrentPassword.getText(), pbNewPassword.getText(), pbConfirmNewPassword.getText(), false);

    }

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

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

        btnSave.dispose();
    }

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

    private void setButtonClickListener() {
        btnSave.setOnClickListener(v -> {
            if (pbNewPassword != null && pbCurrentPassword != null && pbConfirmNewPassword != null && isAdded()) {
                mPresenter.saveClicked(pbCurrentPassword.getText(), pbNewPassword.getText(), pbConfirmNewPassword.getText());
            }
        });

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


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

    private void setInputFieldFont() {
        pbCurrentPassword.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbCurrentPassword.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbCurrentPassword.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());

        pbNewPassword.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbNewPassword.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbNewPassword.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());

        pbConfirmNewPassword.setTooltipTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbConfirmNewPassword.setEditTextTypeface(FontUtils.getInstance().getDinAlternateBold());
        pbConfirmNewPassword.setTextInputTypeface(FontUtils.getInstance().getDinAlternateBold());

    }

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

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

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

    private void setInputFieldTextWatcher() {

        pbCurrentPassword.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) {
                pbCurrentPassword.resetError();
                mPresenter.validateFields(pbCurrentPassword.getText(), pbNewPassword.getText(), pbConfirmNewPassword.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        pbNewPassword.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) {
                pbNewPassword.resetError();
                mPresenter.validateFields(pbCurrentPassword.getText(), pbNewPassword.getText(), pbConfirmNewPassword.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pbConfirmNewPassword.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) {
                pbConfirmNewPassword.resetError();
                mPresenter.validateFields(pbCurrentPassword.getText(), pbNewPassword.getText(), pbConfirmNewPassword.getText(), false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    @Override
    public void setPresenter(EditPasswordContract.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);
    }

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

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

    @Override
    public void showInvalidPasswordError() {
        if (pbNewPassword != null && isAdded()) {
            pbNewPassword.showError(getString(R.string.invalid_password));
        }
    }

    @Override
    public void showPasswordsDontMatchError() {
        if (pbConfirmNewPassword != null && isAdded()) {
            pbConfirmNewPassword.showError(getString(R.string.password_no_match));
        }

    }

    @Override
    public void showIncorrectPasswordError() {
        if (pbCurrentPassword != null && isAdded()) {
            pbCurrentPassword.showError(getString(R.string.current_password_incorrect));
        }
    }

    @Override
    public void showCurrentPasswordError() {
        if (pbCurrentPassword != null && isAdded()) {
            pbCurrentPassword.showError(getString(R.string.current_password_invalid));
        }

    }

    @Override
    public void showSingleButtonDialog(String error, String message) {
        if (mListener != null)
            mListener.showSingleButtonDialog(error, message, null);
    }
}
