package com.gh.gamecenter.personal;

import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.DownloadItemUtils;
import com.gh.common.util.GameViewUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.view.CardLinearLayout;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.adapter.viewholder.NoDataSkipViewHolder;
import com.gh.gamecenter.db.info.ConcernInfo;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.manager.ConcernManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by LGT on 2016/8/15.
 */
public class ConcernFragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;

    private RecyclerView fm_concern_rv_show;

    private List<ConcernInfo> concernList;
    private List<GameEntity> gameList;

    //下载用到的map
    private ArrayMap<String, Integer> locationMap;
    private ArrayMap<String, String> nameMap;

    private boolean isRemove;
    private boolean isEmpty;

    public ConcernFragmentAdapter(Context context, RecyclerView recyclerView) {
        this.context = context;

        fm_concern_rv_show = recyclerView;

        isRemove = false;
        isEmpty = false;

        gameList = new ArrayList<>();

        locationMap = new ArrayMap<>();
        nameMap = new ArrayMap<>();

        ConcernManager concernManager = new ConcernManager(context);
        concernList = concernManager.getConcernGame();

        if (concernList == null || concernList.isEmpty()) {
            isEmpty = true;
        } else {
            init();
        }
    }

    private int count;

    private void addCount() {
        synchronized (ConcernFragmentAdapter.class) {
            count++;
        }
    }

    private void init() {
        final List<JSONObject> result = new ArrayList<>();
        final int size = concernList.size();
        count = 0;
        for (int i = 0; i < concernList.size(); i++) {
            JsonObjectExtendedRequest concernObjectRequest = new JsonObjectExtendedRequest(
                    TimestampUtils.addTimestamp(
                            Config.HOST + "v2d0/game/" + concernList.get(i).getId() + "/digest",
                            Constants.GAME_CD),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            result.add(response);
                            addCount();
                            if (count == size) {
                                processingConcernGame(result);
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            addCount();
                            if (count == size) {
                                processingConcernGame(result);
                            }
                        }
                    });
            AppController.addToRequestQueue(concernObjectRequest, ConcernFragment.TAG);
        }
    }

    private void processingConcernGame(List<JSONObject> data) {
        List<GameEntity> list = new ArrayList<>();
        Gson gson = new Gson();
        for (int i = 0; i < data.size(); i++) {
            list.add(gson.fromJson(data.get(i).toString(), GameEntity.class));
        }
        for (int i = 0, sizei = concernList.size(); i < sizei; i++) {
            for (int j = 0, sizej = list.size(); j < sizej; j++) {
                if (concernList.get(i).getId().equals(list.get(j).getId())) {
                    gameList.add(list.get(j));
                    break;
                }
            }
        }
        if (gameList.size() != 0) {
            GameManager manager = new GameManager(context);
            for (GameEntity gEntity : gameList) {
                gEntity.setEntryMap(DownloadManager.getInstance(context).getEntryMap(gEntity.getName()));
                manager.addOrUpdate(gEntity.getApk(), gEntity.getId(), gEntity.getName());
            }

            isRemove = true;
            notifyDataSetChanged();

            initLocationMap();
        }
    }

    private void initLocationMap() {
        for (int i = 0; i < gameList.size(); i++) {
            GameEntity gameEntity = gameList.get(i);
            locationMap.put(gameEntity.getName(), i);
            for (ApkEntity apkEntity : gameEntity.getApk()) {
                nameMap.put(apkEntity.getPackageName(), gameEntity.getName());
            }
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.game_normal_item, parent, false);
            return new GameNormalViewHolder(view);
        } else if (isEmpty) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.reuse_nodata_skip, parent, false);
            return new NoDataSkipViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof GameNormalViewHolder && gameList.size() > position) {
            initGameNormal((GameNormalViewHolder) holder, gameList.get(position), position);
        } else if (holder instanceof NoDataSkipViewHolder) {
            NoDataSkipViewHolder viewHolder = (NoDataSkipViewHolder) holder;

            viewHolder.reuse_nodata_skip_tv_hint.setText("暂无关注");
            viewHolder.reuse_nodata_skip_tv_btn.setText("查看精品推荐");
            viewHolder.reuse_nodata_skip_tv_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new EBSkip("GameFragment", 1));
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if (gameList.isEmpty() && (isEmpty || !isRemove)) {
            return 1;
        }
        if (isRemove) {
            return gameList.size();
        }
        return gameList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (gameList.size() != 0 && position >= 0 && position < gameList.size()) {
            return 1;
        }
        return 0;
    }

    private void initGameNormal(final GameNormalViewHolder holder, final GameEntity gameEntity, int i) {

        // 第一个
        if (i == 0) {
            ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
        } else {
            ((CardLinearLayout) holder.itemView).setmTop(0);
        }

        // 最后一个
        if (i == gameList.size() - 1) {
            ((CardLinearLayout) holder.itemView).setBottom(true);
        } else {
            ((CardLinearLayout) holder.itemView).setBottom(false);
        }

        ImageUtils.getInstance(context).display(gameEntity.getIcon(), holder.gameThumb);
        holder.gameNameAndSize.setText(gameEntity.getName());

        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.gameDes.setText(gameEntity.getBrief());
        } else {
            holder.gameDes.setText(gameEntity.getApk().get(0).getSize() + "  " + gameEntity.getBrief());
        }
        GameViewUtils.setLabelList(context,  holder.labelList, gameEntity.getTag());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> kv = new HashMap<>();
                kv.put("名字", gameEntity.getName());
                kv.put("位置", String.valueOf(holder.getPosition() + 1));
                DataUtils.onEvent(context, "点击", "我的光环-已关注", kv);

                Map<String, Object> map = new HashMap<>();
                map.put("location", "列表");
                map.put("page", "我的光环-已关注");
                map.put("game", gameEntity.getName());
                map.put("game_id", gameEntity.getId());
                DataCollectionManager.onEvent(context, "click-item", map);

                AppController.put("GameEntity", gameEntity);
                Intent intent = new Intent(context, GameDetailActivity.class);
                intent.putExtra("entrance", "(我的光环-已关注)");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });

        DownloadItemUtils.setOnClickListener(context, holder.downloadBtn, gameEntity, i,
                this, "(我的光环-已关注)", "我的光环-已关注" + ":" + gameEntity.getName());

        DownloadItemUtils.updateItem(context, holder.gameDes,
                holder.game_progressbar, holder.game_ll_info, holder.download_speed,
                holder.download_percentage, holder.downloadBtn, gameEntity);
    }

    public ArrayMap<String, Integer> getLocationMap() {
        return locationMap;
    }

    public ArrayMap<String, String> getNameMap() {
        return nameMap;
    }

    public List<GameEntity> getGameList() {
        return gameList;
    }

    public boolean isEmpty() {
        return isEmpty;
    }
}
