package co.pixelbeard.theanfieldwrap.writingDetails;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;

import org.parceler.Parcels;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.Article;
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.AnalyticsConstants;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.DateUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.GlideApp;
import co.pixelbeard.theanfieldwrap.utils.ScreenUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import co.pixelbeard.theanfieldwrap.utils.TextUtils;
import io.realm.Realm;

public class WritingDetailsFragment extends BaseFragment implements WritingDetailContract.View {

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

    @BindView(R.id.ll_back)
    LinearLayout llBack;

    @BindView(R.id.txt_article_date)
    TextView txtArticleDate;
    @BindView(R.id.txt_article_name)
    TextView txtArticleName;
    @BindView(R.id.txt_author_name)
    TextView txtAuthorName;
    @BindView(R.id.txt_written_by)
    TextView txtWrittenBy;


    @BindView(R.id.img_writing_header)
    ImageView imgWritingHeader;
    @BindView(R.id.cl_writing_header)
    ConstraintLayout clWritingHeader;
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;

    @BindView(R.id.ll_gradient_container)
    LinearLayout llGradientContainer;


    @BindView(R.id.rv_writing_details)
    RecyclerView rvWritingDetails;

    private static final String ARTICLE = "ARTICLE";
    private static final String ARTICLE_ID = "ARTICLE_ID";

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


    private Article mArticle;
    private Long mArticleId;

    private WritingDetailContract.Presenter mPresenter;

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

    public static WritingDetailsFragment newInstance(Article article) {
        WritingDetailsFragment fragment = new WritingDetailsFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARTICLE, Parcels.wrap(article));
        fragment.setArguments(args);
        return fragment;
    }

    public static WritingDetailsFragment newInstance(Long articleId) {
        WritingDetailsFragment fragment = new WritingDetailsFragment();
        Bundle args = new Bundle();
        args.putLong(ARTICLE_ID, articleId);
        fragment.setArguments(args);
        return fragment;
    }

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

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mArticle = Parcels.unwrap(getArguments().getParcelable(ARTICLE));
            mArticleId = getArguments().getLong(ARTICLE_ID);
        }

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

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

        setTextViewFonts();

        setButtonClickListeners();
        rvWritingDetails.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));

        appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
            double currentOffset = (double) i;
            double percentage = (currentOffset / -appBarLayout.getTotalScrollRange());

            imgWritingHeader.setScaleX(1 + (float) percentage);
            imgWritingHeader.setScaleY(1 + (float) percentage);

            txtArticleDate.setTranslationY(i * 0.7f);
            txtArticleName.setTranslationY(i * 0.6f);
            txtAuthorName.setTranslationY(i * 0.55f);
            txtWrittenBy.setTranslationY(i * 0.55f);
            llGradientContainer.setTranslationY(i * 0.5f);
        });

        clWritingHeader.getLayoutParams().height = (int) (ScreenUtils.getScreenHeight(mContext) * 0.7);
    }

    @Override
    public void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);
        if (mArticle != null) {
            setArticle(mArticle);
        } else {
            mPresenter.getArticleById(mArticleId);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mArticle != null) {
            mPresenter.recordAnalytic(AnalyticsConstants.STOPPED_VIEWING_ARTICLE, String.valueOf(mArticle.getPostId()), "1");
        } else if (mArticleId != null) {
            mPresenter.recordAnalytic(AnalyticsConstants.STOPPED_VIEWING_ARTICLE, String.valueOf(mArticleId), "1");
        }
    }

    private void setTextViewFonts() {
        txtArticleName.setTypeface(FontUtils.getInstance().getRobotoBold());
        txtArticleDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtAuthorName.setTypeface(FontUtils.getInstance().getDinProBlack());
        txtWrittenBy.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setButtonClickListeners() {
        llBack.setOnClickListener(v -> mListener.goBack());
    }

    private void setData() {
        GlideApp.with(mContext)
                .load(mArticle.getLargeImage())
                .placeholder(R.drawable.ic_placeholder_writing_large)
                .into(imgWritingHeader);


        TextUtils.setTextPaddingColor(txtArticleName, Html.fromHtml(mArticle.getTitle()).toString(), mContext);
        txtArticleDate.setText(DateUtils.getDateddMMYYYY(mArticle.getCreatedDate()));
        txtAuthorName.setText(mArticle.getAuthor());

        try {
            parseContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseContent() {

        new Thread(() -> {
            if (mArticle != null) {
                String content = mArticle.getContent();

                if (content != null) {
                    content = content.replaceAll("\\[img]", "::");
                    content = content.replaceAll("\\[/img]", "::");

                    String[] strings = content.split("::");


                    WritingContentAdapter adapter = new WritingContentAdapter(strings);

                    ((AppCompatActivity) mContext).runOnUiThread(() ->
                            rvWritingDetails.setAdapter(adapter));
                }
            }
        }).start();
    }

    @Override
    public void setArticle(Article article) {
        this.mArticle = article;
        mPresenter.recordAnalytic(AnalyticsConstants.VIEWED_ARTICLE, String.valueOf(article.getPostId()), "1");
        if (isAdded() && !isDetached()) {
            setData();
        }
    }

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

    @Override
    public void goBack() {
        mListener.goBack();
    }

    @Override
    public void showLoader(String text) {
        mListener.showLoader(text);
    }

    @Override
    public void hideLoader() {
        new Handler().postDelayed(() -> mListener.hideLoader(), 300);
    }

    @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);
    }
}
