package com.gh.gamecenter.info;

import android.content.Context;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage1ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage2ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage3ViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.databinding.NewsImage1ItemBinding;
import com.gh.gamecenter.databinding.NewsImage2ItemBinding;
import com.gh.gamecenter.databinding.NewsImage3ItemBinding;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.manager.VisitManager;
import com.gh.gamecenter.common.retrofit.JSONObjectResponse;
import com.gh.gamecenter.retrofit.RetrofitManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by khy on 2016/6/30.
 * 资讯-资讯-数据适配器
 */
class InfoAdapter extends ListAdapter<NewsEntity> {

    private OnListClickListener mListListener;

    InfoAdapter(Context context, OnListClickListener listListener) {
        super(context);
        this.mListListener = listListener;
    }

    @Override
    protected boolean areItemsTheSame(NewsEntity oldItem, NewsEntity newItem) {
        return !TextUtils.isEmpty(oldItem.getId()) && oldItem.getId().equals(newItem.getId());
    }

    @Override
    protected boolean areContentsTheSame(NewsEntity oldItem, NewsEntity newItem) {
        return oldItem.getViews() == newItem.getViews();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case ItemViewType.NEWS_IMAGE1:
                return new NewsImage1ViewHolder(NewsImage1ItemBinding.inflate(mLayoutInflater, parent, false), mListListener);
            case ItemViewType.NEWS_IMAGE2:
                return new NewsImage2ViewHolder(NewsImage2ItemBinding.inflate(mLayoutInflater, parent, false), mListListener);
            case ItemViewType.NEWS_IMAGE3:
                return new NewsImage3ViewHolder(NewsImage3ItemBinding.inflate(mLayoutInflater, parent, false), mListListener);
            case ItemViewType.LOADING:
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view, mListListener);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ItemViewType.NEWS_IMAGE1:
                initNewsImage1ViewHolder((NewsImage1ViewHolder) holder, position);
                break;
            case ItemViewType.NEWS_IMAGE2:
                initNewsImage2ViewHolder((NewsImage2ViewHolder) holder, position);
                break;
            case ItemViewType.NEWS_IMAGE3:
                initNewsImage3ViewHolder((NewsImage3ViewHolder) holder, position);
                break;
            case ItemViewType.LOADING:
                FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
                footerViewHolder.initItemPadding();
                footerViewHolder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver);
                break;
        }
    }

    private void initNewsImage1ViewHolder(final NewsImage1ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        ImageUtils.display(viewHolder.binding.newsImage1Thumb, newsEntity.getThumbnail().getUrl().get(0));
        viewHolder.binding.newsImage1Title.setText(newsEntity.getTitle());
        viewHolder.binding.newsImage1Title.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.title));

        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage1Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage1Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage1Read.setText(String.format(Locale.getDefault(), "阅读 %s", NumberUtils.transSimpleCount(views)));
        }
        viewHolder.binding.newsImage1Read.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.content));
        NewsUtils.setNewsType(viewHolder.binding.newsImage1Type, newsEntity.getType(), newsEntity.getPriority(), position);
        viewHolder.itemView.setBackground(ContextCompat.getDrawable(viewHolder.itemView.getContext(), R.drawable.reuse_listview_item_style));
    }

    private void initNewsImage2ViewHolder(final NewsImage2ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        DisplayMetrics outMetrics = new DisplayMetrics();
        int width = (outMetrics.widthPixels - DisplayUtils.dip2px(mContext, 56)) / 3;
        int height = (int) (width * 3 / 4f);

        LinearLayout.LayoutParams lparams1 = new LinearLayout.LayoutParams(width, height);
        viewHolder.binding.newsImage2Thumb1.setLayoutParams(lparams1);

        LinearLayout.LayoutParams lparams2 = new LinearLayout.LayoutParams(width, height);
        lparams2.leftMargin = DisplayUtils.dip2px(mContext, 8);
        viewHolder.binding.newsImage2Thumb2.setLayoutParams(lparams2);

        LinearLayout.LayoutParams lparams3 = new LinearLayout.LayoutParams(width, height);
        lparams3.leftMargin = DisplayUtils.dip2px(mContext, 8);
        viewHolder.binding.newsImage2Thumb3.setLayoutParams(lparams3);

        viewHolder.binding.newsImage2Title.setText(newsEntity.getTitle());
        viewHolder.binding.newsImage2Title.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.title));

        ImageUtils.display(viewHolder.binding.newsImage2Thumb1, newsEntity.getThumbnail().getUrl().get(0));
        ImageUtils.display(viewHolder.binding.newsImage2Thumb2, newsEntity.getThumbnail().getUrl().get(1));
        ImageUtils.display(viewHolder.binding.newsImage2Thumb3, newsEntity.getThumbnail().getUrl().get(2));
        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage2Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage2Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage2Read.setText(String.format(Locale.getDefault(), "阅读 %s", NumberUtils.transSimpleCount(views)));
        }
        viewHolder.binding.newsImage2Read.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.content));
        NewsUtils.setNewsType(viewHolder.binding.newsImage2Type, newsEntity.getType(), newsEntity.getPriority(), position);
        viewHolder.itemView.setBackground(ContextCompat.getDrawable(viewHolder.itemView.getContext(), R.drawable.reuse_listview_item_style));
    }

    private void initNewsImage3ViewHolder(final NewsImage3ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        viewHolder.binding.newsImage3Title.setText(newsEntity.getTitle());
        viewHolder.binding.newsImage3Title.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.title));

        ImageUtils.display(viewHolder.binding.newsImage3Thumb, newsEntity.getThumbnail().getUrl().get(0),
                mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(mContext, 40));
        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage3Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage3Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage3Read.setText(String.format(Locale.getDefault(), "阅读 %s", NumberUtils.transSimpleCount(views)));
        }
        viewHolder.binding.newsImage3Read.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.content));
        NewsUtils.setNewsType(viewHolder.binding.newsImage3Type, newsEntity.getType(), newsEntity.getPriority(), position);
        viewHolder.itemView.setBackground(ContextCompat.getDrawable(viewHolder.itemView.getContext(), R.drawable.reuse_listview_item_style));
    }


    // 统计新闻阅读量
    public void statNewsViews(final NewsEntity newsEntity, final int position) {
        RetrofitManager.getInstance().getApi().postArticleVisit(newsEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new JSONObjectResponse() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response.length() != 0) {
                            try {
                                if ("success".equals(response.getString("status"))) {
                                    newsEntity.setViews(newsEntity.getViews() + 1);

                                    notifyItemChanged(position);

                                    // 更新okhttp缓存数据
                                    VisitManager.updateOkhttpCache(mContext, newsEntity.getId());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return ItemViewType.LOADING;
        }
        NewsEntity newsEntity = mEntityList.get(position);
        if ("4x3".equals(newsEntity.getThumbnail().getType()) && newsEntity.getThumbnail().getUrl().size() == 3) {
            return ItemViewType.NEWS_IMAGE2;
        }
        if ("3x1".equals(newsEntity.getThumbnail().getType())) {
            return ItemViewType.NEWS_IMAGE3;
        }
        return ItemViewType.NEWS_IMAGE1;
    }

    @Override
    public int getItemCount() {
        return mEntityList == null || mEntityList.isEmpty() ? 0 : mEntityList.size() + FOOTER_ITEM_COUNT;
    }
}
