package com.gh.gamecenter;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.base.DetailActivity;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DataUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBConcernChanged;
import com.gh.gamecenter.gamedetail.GameDetailAdapter;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by khy on 2016/8/12.
 */
public class GameDetailActivity extends DetailActivity implements View.OnClickListener{

    public static final String TAG = GameDetailActivity.class.getSimpleName();

    private GameDetailAdapter adapter;

    private String gameId;

    private long start;

    private boolean isSentReport;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        AppController.put("GameEntity", gameEntity);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        start = System.currentTimeMillis();

        name = "游戏详情";
        isSentReport = false;

        gameId = getIntent().getStringExtra("gameId");
        if (gameId == null) {
            gameEntity = (GameEntity) AppController.get("GameEntity", true);
            if (gameEntity != null) {
                gameId = gameEntity.getId();
                title = gameEntity.getName();
                actionbar_tv_title.setText(gameEntity.getName());
            }
        }

        adapter = new GameDetailAdapter(this, gameId, entrance);
        detail_rv_show.setLayoutManager(new LinearLayoutManager(this));
        detail_rv_show.setAdapter(adapter);

        detail_ll_bottom.setOnClickListener(this);
        detail_tv_download.setOnClickListener(this);
        detail_tv_per.setOnClickListener(this);
        reuse_no_connection.setOnClickListener(this);

        if (gameEntity != null) {
            adapter.setGameEntity(gameEntity);
            adapter.getGameDetail();
        } else {
            getGameDigest();
        }
    }

    @Override
    public void loadDone() {
        if (!isDestroy) {
            if (reuse_ll_loading.getVisibility() == View.VISIBLE) {
                reuse_ll_loading.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(adapter.getGameDetailEntity().getShareCode())) {
                iv_share.setVisibility(View.VISIBLE);
            }
            downloadAddWord = adapter.getGameDetailEntity().getDownloadAddWord();
            initDownload(true);
        }
    }

    @Override
    public void loadError() {
        if (!isDestroy) {
            reuse_ll_loading.setVisibility(View.GONE);
            reuse_no_connection.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == reuse_no_connection) {
            reuse_no_connection.setVisibility(View.GONE);
            reuse_ll_loading.setVisibility(View.VISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (gameEntity != null) {
                        adapter.getGameDetail();
                    } else {
                        getGameDigest();
                    }
                }
            }, 1000);
        } else if (v == iv_share) {
            Map<String, Object> kv = new HashMap<>();
            kv.put("点击", "分享");
            DataUtils.onEvent(this, "插件数据", gameEntity.getName(), kv);

            Map<String, Object> map = new HashMap<>();
            map.put("location", "分享");
            map.put("news", gameEntity.getName());
            map.put("page", "游戏详情");
            DataCollectionManager.onEvent(this, "click-item", map);

            String url = "http://www.ghzhushou.com/game/" + adapter.getGameDetailEntity().getShareCode();
            showShare(url, gameEntity.getName(), gameEntity.getIcon(), null, gameEntity.getTag(), entrance, "游戏");
        }
    }

    // 获取游戏摘要
    private void getGameDigest() {
        String url = TimestampUtils.addTimestamp(Config.HOST + "v2d0/game/" + gameId + "/digest",
                Constants.GAME_CD);
        JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (!isDestroy) {
                            Gson gson = new Gson();
                            gameEntity = gson.fromJson(response.toString(), GameEntity.class);
                            title = gameEntity.getName();
                            actionbar_tv_title.setText(gameEntity.getName());
                            adapter.setGameEntity(gameEntity);
                            adapter.getGameDetail();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        reuse_no_connection.setVisibility(View.VISIBLE);
                    }
                });
        AppController.addToRequestQueue(request, TAG);
    }

    // 关注事件
    public void onEventMainThread(EBConcernChanged changed) {
        if (!TextUtils.isEmpty(gameId) && changed.getGameId().equals(gameId)) {
            adapter.notifyItemChanged(0);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isSentReport) {
            long end = System.currentTimeMillis();

            int seconds = (int) ((end - start) / 1000);

            String cost;
            if (seconds < 5) {
                cost = "小于5秒";
            } else if (seconds < 30) {
                cost = "5秒－30秒";
            } else if (seconds < 60) {
                cost = "30秒－60秒";
            } else {
                cost = "大于60秒";
            }

            if (gameEntity != null && !TextUtils.isEmpty(gameEntity.getName())) {
                Map<String, Object> kv = new HashMap<>();
                kv.put("停留时长", cost);
                DataUtils.onEvent(this, "插件数据", gameEntity.getName(), kv);

                if (seconds > 0) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("game", gameEntity.getName());
                    map.put("game_id", gameEntity.getId());
                    map.put("time", seconds);
                    map.put("from", entrance);
                    DataCollectionManager.onEvent(this, "game", map);
                }
            }

            isSentReport = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        adapter = null;
    }

}
