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.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.TrafficUtils;
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.entity.MyGameInfo;
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.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

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

    private Context context;

    private RecyclerView fm_install_rv_show;

    private ArrayList<GameEntity> gameList;
    private ArrayList<MyGameInfo> sortedList;

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

    private boolean isRemove;
    private boolean isEmpty;

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

        fm_install_rv_show = recyclerView;

        gameList = new ArrayList<>();
        sortedList = new ArrayList<>();

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

        isRemove = false;
        isEmpty = false;

        ConcernManager cManager = new ConcernManager(context);
        List<ConcernInfo> runnableGame = cManager.getInstalledGame();
        if (runnableGame.isEmpty()) {
            isEmpty = true;
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    init();
                    List<String> ids = new ArrayList<>();
                    for (MyGameInfo info : sortedList) {
                        if (!ids.contains(info.getGame_id())) {
                            ids.add(info.getGame_id());
                        }
                    }
                    initGameList(ids);
                }
            }).start();
        }
    }

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

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

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

    //初始化
    private void init() {

        ArrayList<MyGameInfo> signatureList = new ArrayList<>();
        ArrayList<MyGameInfo> unsignatureList = new ArrayList<>();
        ArrayList<MyGameInfo> noopenList = new ArrayList<>();
        ArrayList<MyGameInfo> oftenuseList = new ArrayList<>();

        TrafficUtils tUtils = TrafficUtils.getInstance(context);

        ConcernManager cManager = new ConcernManager(context);
        List<ConcernInfo> runnableGame = cManager.getInstalledGame();
        for (ConcernInfo concernEntity : runnableGame) {
            for (Map.Entry<String, Boolean> entry : concernEntity.getPackageNames().entrySet()) {
                if (entry.getValue()) {
                    MyGameInfo info = new MyGameInfo();
                    info.setGame_id(concernEntity.getId());
                    info.setPackage_name(entry.getKey());
                    info.setTraffic(tUtils.getTraffice(entry.getKey()));
                    info.setSignature(PackageUtils.isSignature(context, entry.getKey()));
                    info.setInstalledTime(PackageUtils.getInstalledTime(context, entry.getKey()));
                    if (info.isSignature()) {
                        signatureList.add(info);
                    } else {
                        unsignatureList.add(info);
                    }
                }
            }
        }

        for (MyGameInfo info : signatureList) {
            if (info.getTraffic() == 0) {
                noopenList.add(info);
            } else {
                oftenuseList.add(info);
            }
        }

        Comparator<MyGameInfo> comparator = new Comparator<MyGameInfo>() {
            @Override
            public int compare(MyGameInfo lhs, MyGameInfo rhs) {
                if (rhs.getInstalledTime() > lhs.getInstalledTime()) {
                    return 1;
                } else if (rhs.getInstalledTime() < lhs.getInstalledTime()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };

        Collections.sort(noopenList, comparator);

        comparator = new Comparator<MyGameInfo>() {
            @Override
            public int compare(MyGameInfo lhs, MyGameInfo rhs) {
                if (rhs.getTraffic() > lhs.getTraffic()) {
                    return 1;
                } else if (rhs.getTraffic() < lhs.getTraffic()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };

        Collections.sort(oftenuseList, comparator);

        Collections.sort(unsignatureList, comparator);

        sortedList.addAll(noopenList);
        sortedList.addAll(oftenuseList);
        sortedList.addAll(unsignatureList);
    }

    private int count;

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

    //获取游戏简介
    private void initGameList(List<String> ids) {
        final List<JSONObject> result = new ArrayList<>();
        final int size = ids.size();
        count = 0;
        for (int i = 0; i < ids.size(); i++) {
            JsonObjectExtendedRequest objectRequest = new JsonObjectExtendedRequest(
                    TimestampUtils.addTimestamp(
                            Config.HOST + "v2d0/game/" + ids.get(i) + "/digest",
                            Constants.GAME_CD),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            result.add(response);
                            addCount();
                            if (count == size) {
                                processingData(result);
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            addCount();
                            if (count == size) {
                                processingData(result);
                            }
                        }
                    });
            AppController.addToRequestQueue(objectRequest, InstallFragment.TAG);
        }
    }

    private void processingData(List<JSONObject> data) {
        Gson gson = new Gson();
        List<GameEntity> gameList = new ArrayList<>();
        for (int i = 0, size = data.size(); i < size; i++) {
            gameList.add(gson.fromJson(data.get(i).toString(), GameEntity.class));
        }
        if (gameList.size() != 0) {
            for (int i = 0, size = sortedList.size(); i < size; i++) {
                String id = sortedList.get(i).getGame_id();
                for (GameEntity entity : gameList) {
                    if (entity.getId().equals(id)) {
                        GameEntity newEntity = entity.clone();
                        if (newEntity != null && newEntity.getApk().size() > 1) {
                            for (ApkEntity apkEntity : newEntity.getApk()) {
                                if (sortedList.get(i).getPackage_name().equals(apkEntity.getPackageName())) {
                                    ArrayList<ApkEntity> list = new ArrayList<>();
                                    list.add(apkEntity);
                                    newEntity.setApk(list);
                                    break;
                                }
                            }
                        }
                        this.gameList.add(newEntity);
                        break;
                    }
                }
            }
            GameManager manager = new GameManager(context);
            for (GameEntity entity : this.gameList) {
                entity.setEntryMap(DownloadManager.getInstance(context).getEntryMap(entity.getName()));
                manager.addOrUpdate(entity.getApk(), entity.getId(), entity.getName());
            }
        }

        if (this.gameList.size() != 0) {
            ArrayMap<String, ArrayList<GameEntity>> map = new ArrayMap<>();
            ArrayList<String> keys = new ArrayList<>();
            ArrayList<GameEntity> list;
            for (GameEntity gameEntity : this.gameList) {
                list = map.get(gameEntity.getId());
                if (list == null) {
                    list = new ArrayList<>();
                    map.put(gameEntity.getId(), list);
                    keys.add(gameEntity.getId());
                }
                list.add(gameEntity);
            }
            list = new ArrayList<>();
            for (String key : keys) {
                list.addAll(map.get(key));
            }
            this.gameList = list;
            isRemove = true;
            notifyDataSetChanged();

            initLocationMap();
        }
    }

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

    @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) {
            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.itemView.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);

        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.gameDes.setText(gameEntity.getBrief());
            holder.gameNameAndSize.setText(gameEntity.getName());
        } else {
            holder.gameNameAndSize.setText(String.format("%s - %s", gameEntity.getName(),
                    PlatformUtils.getInstance(context).getPlatformName(gameEntity.getApk().get(0).getPlatform())));
            holder.gameDes.setText(String.format("V%s", gameEntity.getApk().get(0).getVersion()));
        }
        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);

                Intent intent = new Intent(context, GameDetailActivity.class);
                intent.putExtra("gameId", gameEntity.getId());
                intent.putExtra("entrance", "(我的光环-已安装)");
                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, false);
    }

    public boolean isEmpty() {
        return isEmpty;
    }
}
