package com.gh.gamecenter.game;

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

import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
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.NewsUtils;
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.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SubjectActivity;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameHeadViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameImageViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameTestViewHolder;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.SubjectEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by khy on 2016/6/28.
 */
public class Game2FragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private class ITEM_TYPE {
        public final static int HEAD = 100;// 专题头部
        public final static int GAME_NORMAL = 101;// 游戏布局1
        public final static int GAME_TEST = 102;// 游戏布局2
        public final static int IMAGE = 103;// 大图布局
        public final static int FOOTER = 104;// 加载布局
    }

    private Game2Fragment fragment;
    private Context context;
    private OnCallBackListener listener;

    private List<SubjectEntity> subjectList;

    private ArrayMap<String, ArrayList<Integer>> locationMap;
    private ArrayMap<String, String> nameMap;

    public Game2FragmentAdapter(Game2Fragment fragment, boolean isLoad) {

        this.fragment = fragment;
        this.context = fragment.getActivity();
        this.listener = fragment;

        subjectList = new ArrayList<>();

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

        if (isLoad) {
            load();
        }
    }

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

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

    public void load() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initSubjectList();
            }
        }).start();
    }

    private void initSubjectList() {
        JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
                TimestampUtils.addTimestamp(Config.HOST + "v1d50/game/tuijian",
                        Constants.GAME_CD),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        Type listType = new TypeToken<ArrayList<SubjectEntity>>() {}.getType();
                        Gson gson = new Gson();
                        List<SubjectEntity> list = gson.fromJson(response.toString(), listType);
                        if (list != null && !list.isEmpty()) {
                            subjectList = list;
                            GameManager manager = new GameManager(context);
                            SubjectEntity subjectEntity;
                            GameEntity gameEntity;
                            for (int j = 0; j < subjectList.size(); j++) {
                                subjectEntity = subjectList.get(j);
                                if (subjectEntity.getData().size() == 1
                                        && !TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())){
                                    subjectList.remove(j);
                                    continue;
                                }
                                for (int i = 0; i < subjectEntity.getData().size(); i++) {
                                    gameEntity = subjectEntity.getData().get(i);
                                    if (gameEntity.getApk() != null && !gameEntity.getApk().isEmpty()) {
                                        gameEntity.setEntryMap(DownloadManager.getInstance(context).getEntryMap(gameEntity.getName()));
                                        manager.addOrUpdate(gameEntity.getApk(), gameEntity.getId(), gameEntity.getName());
                                    } else if (TextUtils.isEmpty(gameEntity.getId())) {
                                        if (TextUtils.isEmpty(gameEntity.getType())
                                                || TextUtils.isEmpty(gameEntity.getLink())
                                                || TextUtils.isEmpty(gameEntity.getName())
                                                || TextUtils.isEmpty(gameEntity.getImage())) {
                                            subjectEntity.getData().remove(i);
                                            i--;
                                        }
                                    }
                                }
                            }

                            if (!fragment.isHidden() && !fragment.isEverpause()) {
                                notifyItemRangeInserted(0, getItemCount());
                            } else {
                                notifyDataSetChanged();
                            }

                            initLocationMap();
                        }

                        listener.loadDone();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 无网络连接和访问超时
                        if (error.getClass().equals(NoConnectionError.class)
                                || error.getClass().equals(TimeoutError.class)) {
                            listener.loadError();
                        }
                    }
                });
        AppController.addToRequestQueue(request, Game2Fragment.TAG);
    }

    private void initLocationMap() {
        locationMap.clear();

        if (!subjectList.isEmpty()) {
            int count = getItemCount() - 1;
            GameEntity gameEntity;
            int offset;
            String name;
            ArrayList<Integer> locationList;
            for (int position = 0; position < count; position++) {
                offset = 0;
                for (int i = 0, size = subjectList.size(); i < size; i++) {
                    if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                        gameEntity = subjectList.get(i).getData().get(position - offset - 1);
                        if (gameEntity.getApk() != null && !gameEntity.getApk().isEmpty()) {
                            name = gameEntity.getName();
                            locationList = locationMap.get(name);
                            if (locationList == null) {
                                locationList = new ArrayList<>();
                                locationMap.put(name, locationList);
                            }
                            locationList.add(position);
                            for (ApkEntity apkEntity : gameEntity.getApk()) {
                                nameMap.put(apkEntity.getPackageName(), name);
                            }
                        }
                        break;
                    }
                    offset = subjectList.get(i).getData().size() + offset + 1;
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        int subjectSize = 0;
        if (!subjectList.isEmpty()) {
            for (int i = 0; i < subjectList.size(); i++) {
                SubjectEntity subjectEntity = subjectList.get(i);
                subjectSize += subjectEntity.getData().size() + 1;
            }
            subjectSize += 1;
        }
        return subjectSize;
    }

    @Override
    public int getItemViewType(int position) {
        if (!subjectList.isEmpty()) {
            int offset = 0;
            GameEntity gameEntity;
            for (int i = 0; i < subjectList.size(); i++) {
                if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                    int index = position -offset-1;
                    if (index < 0) {
                        index = 0;
                    }
                    gameEntity = subjectList.get(i).getData().get(index);
                    if (position == offset && !TextUtils.isEmpty(gameEntity.getImage())){
                        return ITEM_TYPE.IMAGE;
                    }else if (position == offset){
                        return ITEM_TYPE.HEAD;
                    }
                    if (position == offset+1 && !TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())) {
                        return ITEM_TYPE.HEAD;
                    }
                    if (gameEntity.getTest() != null) {
                        return ITEM_TYPE.GAME_TEST;
                    }
                    return ITEM_TYPE.GAME_NORMAL;
                }
                offset = subjectList.get(i).getData().size() + offset + 1;
            }
        }
        return ITEM_TYPE.FOOTER;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE.HEAD) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.home_game_head_item, parent, false);
            return new GameHeadViewHolder(view);
        } else if (viewType == ITEM_TYPE.IMAGE) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.home_game_image_item, parent, false);
            return new GameImageViewHolder(view);
        } else if (viewType == ITEM_TYPE.GAME_TEST) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.game_test_item, parent, false);
            return new GameTestViewHolder(view);
        } else if (viewType == ITEM_TYPE.GAME_NORMAL) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.game_normal_item, parent, false);
            return new GameNormalViewHolder(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 GameHeadViewHolder) {
            initGameHeadViewHolder((GameHeadViewHolder) holder, position);
        } else if (holder instanceof GameNormalViewHolder) {
            initGameNormalViewHolder((GameNormalViewHolder) holder, position);
        } else if (holder instanceof GameTestViewHolder) {
            initGameTestViewHolder((GameTestViewHolder) holder, position);
        } else if (holder instanceof GameImageViewHolder) {
            initGameImageViewHolder((GameImageViewHolder) holder, position);
        } else if (holder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) holder);
        }
    }

    private void initFooterViewHolder(FooterViewHolder holder) {
        holder.footerview_line1.setVisibility(View.VISIBLE);
        holder.footerview_line2.setVisibility(View.VISIBLE);
        holder.footerview_progressbar.setVisibility(View.GONE);
        holder.footerview_tv_loading.setText("到底了哦~");
        holder.itemView.setClickable(false);
    }

    private void initGameHeadViewHolder(GameHeadViewHolder holder, int position) {
        int offset = 0;
        GameEntity gameEntity;
        for (int i = 0; i < subjectList.size(); i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position - offset;
                if (index < 0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (position == offset && TextUtils.isEmpty(gameEntity.getImage())
                        || position == offset + 1 && !TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())) {
                    if (TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())
                            && i == 0) {
                        ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
                    } else {
                        ((CardLinearLayout) holder.itemView).setmTop(0);
                    }
                    holder.thumb.setVisibility(View.GONE);
                    holder.title.setText(subjectList.get(i).getName());

                    if (subjectList.get(i).getData().size()>= Integer.parseInt(subjectList.get(i).getMore())){
                        holder.link.setVisibility(View.GONE);
                    }else {
                        holder.link.setVisibility(View.VISIBLE);
                    }
                    final int ii = i;
                    holder.link.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SubjectEntity subjectEntity = subjectList.get(ii);
                            Intent intent = new Intent(context, SubjectActivity.class);
                            intent.putExtra("id", subjectEntity.getId());
                            intent.putExtra("name", subjectEntity.getName());
                            intent.putExtra("order",subjectEntity.getOrder());
                            intent.putExtra("entrance", "(游戏-推荐:" + subjectEntity.getName() + "-全部)");
                            context.startActivity(intent);
                        }
                    });
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private void initGameNormalViewHolder(GameNormalViewHolder holder, int position) {
        int offset = 0;
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position -offset-1;
                if (index<0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (TextUtils.isEmpty(gameEntity.getImage()) && gameEntity.getTest() == null) {
                    int order = position - offset - 1;
                    if (subjectList.get(i).getData().get(0).getImage() != null) {
                        order--;
                    }
                    initGameNormal(holder, gameEntity, order, subjectList.get(i), i + 1 == size);
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private void initGameNormal(GameNormalViewHolder holder, GameEntity entity,
                                final int i, final SubjectEntity subjectEntity, boolean isBottom) {
        // 最后一个
        ((CardLinearLayout) holder.itemView).setBottom(isBottom);
        if (TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())) {
            if (i + 1 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        } else {
            if (i + 2 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        }
        if (subjectEntity.getOrder()) {
            holder.home1_game_order.setVisibility(View.VISIBLE);
            holder.home1_game_order.setText(String.valueOf(i + 1));
        } else {
            holder.home1_game_order.setVisibility(View.GONE);
        }
        ImageUtils.getInstance(context).display(entity.getIcon(), holder.gameThumb);
        holder.gameNameAndSize.setText(entity.getName());
        if (entity.getApk() == null || entity.getApk().isEmpty()) {
            holder.gameDes.setText(entity.getBrief());
        } else {
            holder.gameDes.setText(String.format("%s  %s", entity.getApk().get(0).getSize(), entity.getBrief()));
        }
        GameViewUtils.setLabelList(context, holder.labelList, entity.getTag());

        final GameEntity gameEntity = entity;

        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(i + 1));
                DataUtils.onEvent(context, "点击", "游戏-推荐-" + subjectEntity.getName(), kv);

                Map<String, Object> map = new HashMap<>();
                map.put("location", subjectEntity.getName() + "-列表");
                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", "(游戏-推荐:" + subjectEntity.getName() + "-列表)");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });
        DownloadItemUtils.setOnClickListener(context, holder.downloadBtn, entity, i,
                Game2FragmentAdapter.this, "(游戏-推荐:" + subjectEntity.getName() + "-列表)",
                "游戏-推荐-" + subjectEntity.getName() + ":" + entity.getName());

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

    private void initGameTestViewHolder(GameTestViewHolder holder, int position) {
        int offset = 0;
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position - offset - 1;
                if (index < 0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (gameEntity.getTest() != null) {
                    int order = position - offset - 1;
                    if (subjectList.get(i).getData().get(0).getImage() != null) {
                        order--;
                    }
                    initGameTest(holder, gameEntity, order, subjectList.get(i), i + 1 == size);
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private void initGameTest(GameTestViewHolder holder, final GameEntity gameEntity,
                              final int i, final SubjectEntity subjectEntity, boolean isBottom) {

        // 最后一个
        ((CardLinearLayout) holder.itemView).setBottom(isBottom);
        if (TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())) {
            if (i + 1 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        } else {
            if (i + 2 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        }

        if (subjectEntity.getOrder()) {
            holder.home2_game_order.setVisibility(View.VISIBLE);
            holder.home2_game_order.setText(String.valueOf(i + 1));
        } else {
            holder.home2_game_order.setVisibility(View.GONE);
        }
        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(String.format("%s  %s", gameEntity.getApk().get(0).getSize(), gameEntity.getBrief()));
        }
        holder.gameTestType.setText(gameEntity.getTest().getType());
        if (gameEntity.getTest().getStart() == 0) {
            holder.gameTestTime.setVisibility(View.GONE);
        } else {
            holder.gameTestTime.setText(GameViewUtils.getGameTestDate(gameEntity.getTest().getStart()));
        }

        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(i + 1));
                DataUtils.onEvent(context, "点击", "游戏-推荐-" + subjectEntity.getName(), kv);

                Map<String, Object> map = new HashMap<>();
                map.put("location", subjectEntity.getName() + "-列表");
                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", "(游戏-推荐:" + subjectEntity.getName() + "-列表)");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });

        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.downloadBtn.setVisibility(View.GONE);
        } else {
            if (gameEntity.getTest().getEnd() == 0) {
                holder.downloadBtn.setVisibility(View.VISIBLE);
                DownloadItemUtils.setOnClickListener(context,
                        holder.downloadBtn, gameEntity, i,
                        Game2FragmentAdapter.this, "(游戏-推荐:" + subjectEntity.getName() + "-列表)",
                        "游戏-推荐-" + subjectEntity.getName() + ":" + gameEntity.getName());
            } else {
                long endTime = Long.valueOf(gameEntity.getTest().getEnd() + "000");
                long todayTime = new Date().getTime();
                if (todayTime > endTime) {
                    // 测试时间已过
                    holder.downloadBtn.setVisibility(View.GONE);
                } else {
                    // 测试时间未过
                    holder.downloadBtn.setVisibility(View.VISIBLE);
                    DownloadItemUtils.setOnClickListener(context,
                            holder.downloadBtn, gameEntity, i,
                            Game2FragmentAdapter.this, "(游戏-推荐:" + subjectEntity.getName() + "-列表)",
                            "游戏-推荐-" + subjectEntity.getName() + ":" + gameEntity.getName());
                }
            }
        }

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

    private void initGameImageViewHolder(GameImageViewHolder holder, int position) {
        int offset = 0;
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position - offset - 1;
                if (index < 0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (position == offset && !TextUtils.isEmpty(gameEntity.getImage())) {
                    if (i == 0) {
                        ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
                    } else {
                        ((CardLinearLayout) holder.itemView).setmTop(0);
                    }
                    final GameEntity entity = gameEntity;
                    final String name = subjectList.get(i).getName();
                    ImageUtils.getInstance(context).display(entity.getImage(), holder.image, R.drawable.preload, context, 16);//默认应该设置占位符，防止图片混乱
                    holder.image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Map<String, Object> kv = new HashMap<>();
                            kv.put("名字", entity.getName());
                            kv.put("位置", "大图");
                            DataUtils.onEvent(context, "点击", "游戏-推荐-" + name, kv);

                            Map<String, Object> map = new HashMap<>();
                            map.put("location", name + "-大图");
                            map.put("page", "游戏-推荐");
                            DataCollectionManager.onEvent(context, "click-item", map);

                            if ("game".equals(entity.getType())) {
                                Intent intent = new Intent(context, GameDetailActivity.class);
                                intent.putExtra("gameId", entity.getLink());
                                intent.putExtra("entrance", "(游戏-推荐:" + name + "-大图)");
                                context.startActivity(intent);
                            } else if ("news".equals(entity.getType())) {
                                // 统计阅读量
                                NewsUtils.statNewsViews(entity.getLink());

                                Intent intent = new Intent(context, NewsDetailActivity.class);
                                intent.putExtra("newsId", entity.getLink());
                                intent.putExtra("entrance", "(游戏-推荐:" + name + "-大图)");
                                context.startActivity(intent);
                            } else if ("column".equals(entity.getType())) {
                                Intent intent = new Intent(context, SubjectActivity.class);
                                intent.putExtra("id", entity.getLink());
                                intent.putExtra("name", entity.getName());
                                intent.putExtra("entrance", "(游戏-推荐:" + name + "-大图)");
                                context.startActivity(intent);
                            }

                        }
                    });
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    public List<SubjectEntity> getSubectList() {
        return subjectList;
    }

}
