package com.gh.gamecenter.qa.answer.draft;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.PermissionHelper;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.common.baselist.ListViewModel;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.databinding.AnswerDraftItemBinding;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity;
import com.gh.gamecenter.qa.entity.AnswerEntity;
import com.gh.gamecenter.qa.myqa.AnswerDraftViewHolder;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Created by khy on 20/12/17.
 */

class AnswerDraftAdapter extends ListAdapter<AnswerEntity> {

    private OnListClickListener mListClickListener;

    private ListViewModel mListViewModel;

    AnswerDraftAdapter(Context context,
                       OnListClickListener listClickListener,
                       ListViewModel longClickListener) {
        super(context);
        mListClickListener = listClickListener;
        mListViewModel = longClickListener;
    }

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

    @Override
    protected boolean areContentsTheSame(AnswerEntity oldItem, AnswerEntity newItem) {
        return oldItem == newItem;
    }

    @Override
    protected void setListData(List<AnswerEntity> updateData) {
        if (updateData != null && mEntityList != null && updateData.size() == mEntityList.size()) {
            mEntityList = new ArrayList<>(updateData);
            notifyDataSetChanged();
            return;
        }
        super.setListData(updateData);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) return ItemViewType.ITEM_FOOTER;
        return ItemViewType.ITEM_BODY;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case ItemViewType.ITEM_FOOTER:
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view, mListClickListener);
            case ItemViewType.ITEM_BODY:
                view = mLayoutInflater.inflate(R.layout.answer_draft_item, parent, false);
                return new AnswerDraftViewHolder(AnswerDraftItemBinding.bind(view));
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ItemViewType.ITEM_BODY:
                AnswerDraftViewHolder draftViewHolder = (AnswerDraftViewHolder) holder;
                AnswerEntity answerEntity = mEntityList.get(position);
                AnswerDraftItemBinding binding = draftViewHolder.getBinding();
                SimpleDraweeView img = binding.answerDraftItemImg;
                binding.answerDraftItemTitle.setText(answerEntity.getQuestions().getTitle());
                binding.answerDraftItemContent.setText(answerEntity.getBrief());
                binding.answerDraftItemCommunityName.setText(answerEntity.getCommunityName());

                List<String> images = answerEntity.getImages();
                if (images.size() > 0) {
                    for (int i = 0; i < images.size(); i++) {
                        if (!images.get(i).contains(".gif")) {
                            img.setVisibility(View.VISIBLE);
                            ImageUtils.display(img, images.get(i));
                            break;
                        }
                        if (i == images.size() - 1) {
                            img.setVisibility(View.GONE);
                        }
                    }
                } else {
                    img.setVisibility(View.GONE);
                }
                binding.answerDraftItemDelete.setOnClickListener(v -> {
                    DialogHelper.showDialog(mContext, "警告", "确定要删除回答草稿吗？删除之后不可恢复", "确定", "取消", () -> deleteAnswerDraft(answerEntity), () -> {
                    }, false, "", "");
                });
                draftViewHolder.itemView.setOnClickListener(v -> {
                    PermissionHelper.checkStoragePermissionBeforeAction(mContext, () -> {
                        if (mContext instanceof AnswerDraftActivity) {
                            // 不需要回传任何数据
                            ((AnswerDraftActivity) mContext).setResult(Activity.RESULT_OK);
                            ((AnswerDraftActivity) mContext).finish();
                        } else if (answerEntity.getAnswerId().isEmpty()) {
                            mContext.startActivity(AnswerEditActivity.Companion.getIntent(
                                    mContext,
                                    answerEntity.getQuestions(),
                                    answerEntity.getId(),
                                    true,
                                    answerEntity.getCommunityName()));
                        } else {
                            mContext.startActivity(AnswerEditActivity.Companion.getIntent(
                                    mContext,
                                    answerEntity.getAnswerId(),
                                    answerEntity.getQuestions(),
                                    "",//  会自动获取草稿所以该数据可以不填
                                    answerEntity.getCommunityName(),
                                    true,
                                    true));
                        }
                    });
                });
                break;
            case ItemViewType.ITEM_FOOTER:
                FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
                footerViewHolder.initItemPadding();
                footerViewHolder.initFooterViewHolder(mListViewModel, mIsLoading, mIsNetworkError, mIsOver);
                break;
        }
    }

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


    private void deleteAnswerDraft(AnswerEntity entity) {
        RetrofitManager.getInstance()
                .getApi()
                .deleteAnswerDrafts(UserManager.getInstance().getUserId(), entity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<ResponseBody>() {
                    @Override
                    public void onResponse(ResponseBody response) {
                        mListViewModel.load(LoadType.REFRESH);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        Utils.toast(mContext, R.string.loading_network_error);
                    }
                });
    }
}
