package com.gh.gamecenter.game;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gc.materialdesign.views.ProgressBarCircularIndeterminate;
import com.gh.base.AppController;
import com.gh.base.BaseFragment;
import com.gh.common.util.DownloadItemUtils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.SubjectEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.eventbus.EBUISwitch;

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

/**
 * Created by khy on 2016/6/28.
 */
public class Game2Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

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

    private SwipeRefreshLayout fm_game_swipe_refresh;
    private RecyclerView fm_game_rv_list;
    private Game2FragmentAdapter adapter;
    private LinearLayout reuse_no_connection;
    private ProgressBarCircularIndeterminate fm_game_pb_loading;

    private boolean isEverpause;

    private Handler handler = new Handler();

    DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            if (!fm_game_swipe_refresh.isRefreshing()) {
                ArrayList<Integer> locationList = adapter.getLocationMap().get(downloadEntity.getName());
                if (locationList != null && locationList.size() != 0) {
                    for (int location : locationList) {
                        GameEntity detailedEntity = getEntityByLocation(location);
                        if (detailedEntity != null) {
                            DownloadItemUtils.processDate(getActivity(), detailedEntity,
                                    downloadEntity, adapter, location);
                        }
                    }
                }
            }
        }
    };

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

        init(R.layout.fragment_game);

        isEverpause = false;

        reuse_no_connection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm_game_swipe_refresh.setRefreshing(true);
                fm_game_rv_list.setVisibility(View.VISIBLE);
                fm_game_pb_loading.setVisibility(View.VISIBLE);
                reuse_no_connection.setVisibility(View.GONE);
                handler.postDelayed(runnable, 1000);
            }
        });

        fm_game_swipe_refresh.setColorSchemeResources(R.color.theme);
        fm_game_swipe_refresh.setOnRefreshListener(this);

        fm_game_rv_list.setHasFixedSize(true);
        fm_game_rv_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new Game2FragmentAdapter(Game2Fragment.this, false);
        fm_game_rv_list.setAdapter(adapter);
    }

    @Override
    public void loadDone() {
        if (fm_game_swipe_refresh != null && fm_game_swipe_refresh.isRefreshing()) {
            fm_game_swipe_refresh.setRefreshing(false);
        }
        if (fm_game_pb_loading != null && fm_game_pb_loading.getVisibility() == View.VISIBLE) {
            fm_game_pb_loading.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadError() {
        Toast.makeText(getActivity(), "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
        if (fm_game_swipe_refresh != null && fm_game_swipe_refresh.isRefreshing()) {
            fm_game_swipe_refresh.setRefreshing(false);
        }
        if (fm_game_pb_loading != null && fm_game_pb_loading.getVisibility() == View.VISIBLE) {
            fm_game_pb_loading.setVisibility(View.GONE);
        }
        fm_game_rv_list.setVisibility(View.GONE);
        reuse_no_connection.setVisibility(View.VISIBLE);
    }

    //下载被删除事件
    public void onEventMainThread(EBDownloadStatus status) {
        if ("delete".equals(status.getStatus())) {
            DownloadManager.getInstance(getActivity()).removePlatform(status.getName(), status.getPlatform());

            ArrayList<Integer> locationList = adapter.getLocationMap().get(status.getName());
            if (locationList != null && locationList.size() != 0) {
                for (int location : locationList) {
                    GameEntity detailedEntity = getEntityByLocation(location);
                    if (detailedEntity != null) {
                        if (TextUtils.isEmpty(status.getPlatform())) {
                            detailedEntity.getEntryMap().remove("官方版");
                        } else {
                            detailedEntity.getEntryMap().remove(status.getPlatform());
                        }
                    }
                    adapter.notifyItemChanged(location);
                }
            }
        }
    }

    // 打开下载按钮事件
    public void onEventMainThread(EBReuse reuse) {
        if ("Refresh".equals(reuse.getType()) && adapter != null) {
            adapter.notifyItemRangeChanged(0, adapter.getItemCount());
        }
    }

    //安装、卸载事件
    public void onEventMainThread(EBPackage busFour) {
        String name = adapter.getNameMap().get(busFour.getPackageName());
        if (name != null) {
            ArrayList<Integer> locationList = adapter.getLocationMap().get(name);
            if (locationList != null && locationList.size() != 0) {
                for (int location : locationList) {
                    if ("安装".equals(busFour.getType())) {
                        GameEntity detailedEntity = getEntityByLocation(location);
                        if (detailedEntity != null) {
                            for (ApkEntity apkEntity : detailedEntity.getApk()) {
                                if (apkEntity.getPackageName().equals(
                                        busFour.getPackageName())) {
                                    detailedEntity.getEntryMap().remove(
                                            apkEntity.getPlatform());
                                    adapter.notifyItemChanged(location);
                                    break;
                                }
                            }
                        }
                    } else if ("卸载".equals(busFour.getType())) {
                        adapter.notifyItemChanged(location);
                    }
                }
            }
        }
    }

    //连接上网络事件
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (reuse_no_connection.getVisibility() == View.VISIBLE) {
                fm_game_swipe_refresh.setRefreshing(true);
                fm_game_rv_list.setVisibility(View.VISIBLE);
                fm_game_pb_loading.setVisibility(View.GONE);
                reuse_no_connection.setVisibility(View.GONE);
                handler.postDelayed(runnable, 1000);
            }
        }
    }

    //Fragment界面切换事件
    public void onEventMainThread(EBUISwitch busNine) {
        if ("GameFragment".equals(busNine.getFrom())) {
            if (busNine.getPosition() == 1) {
                if (fm_game_pb_loading.getVisibility() == View.VISIBLE) {
                    adapter.load();
                }
            }
        }
    }

    private GameEntity getEntityByLocation(int position) {
        List<SubjectEntity> list = adapter.getSubectList();
        int offset = 0;
        for (int i = 0; i < list.size(); i++) {
            if (position > offset && position <= list.get(i).getData().size() + offset) {
                return list.get(i).getData().get(position - offset - 1);
            }
            offset = list.get(i).getData().size() + offset + 1;
        }
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isEverpause) {
            for (SubjectEntity subjectEntity : adapter.getSubectList()) {
                for (GameEntity entity :subjectEntity.getData()) {
                    entity.setEntryMap(DownloadManager.getInstance(getActivity()).getEntryMap(entity.getName()));
                }
            }
            adapter.notifyDataSetChanged();
        }
        isEverpause = false;
        DownloadManager.getInstance(getActivity()).addObserver(dataWatcher);
    }

    @Override
    public void onPause() {
        super.onPause();
        isEverpause = true;
        DownloadManager.getInstance(getActivity()).removeObserver(dataWatcher);
    }

    public boolean isEverpause() {
        return isEverpause;
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isDestroy) {
                adapter = new Game2FragmentAdapter(Game2Fragment.this, true);
                fm_game_rv_list.setAdapter(adapter);
            }
        }
    };

    @Override
    public void onRefresh() {
        handler.postDelayed(runnable, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        fm_game_rv_list = null;
        adapter = null;
        reuse_no_connection = null;
        fm_game_swipe_refresh = null;
        fm_game_pb_loading = null;
        handler = null;
        dataWatcher = null;
    }
}
