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 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 com.gh.gamecenter.manager.PackageManager;

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

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

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

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

    private int currentItem;

    private boolean isEverpause;

    private Handler handler = new Handler();

    private 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);
                        }
                    }
                }

                //特殊 插件化update
                if (downloadEntity.isPluggable()) {
                    locationList = adapter.getLocationMap().get(downloadEntity.getName()
                            + " - " + downloadEntity.getPlatform());
                    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);

        currentItem = 0;

        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 Game1FragmentAdapter(Game1Fragment.this, fm_game_swipe_refresh, 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() {
        fm_game_rv_list.setVisibility(View.GONE);
        fm_game_pb_loading.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());
            GameEntity detailedEntity;
            if (locationList != null && locationList.size() != 0) {
                for (int location : locationList) {
                    detailedEntity = getEntityByLocation(location);
                    if (detailedEntity != null) {
                        if (TextUtils.isEmpty(status.getPlatform())) {
                            detailedEntity.getEntryMap().remove("官方版");
                        } else {
                            detailedEntity.getEntryMap().remove(status.getPlatform());
                        }
                    }
                    adapter.notifyItemChanged(location);
                }
            }
            //特殊 插件化update
            if (status.isPluggable()) {
                locationList = adapter.getLocationMap().get(status.getName() + " - " + status.getPlatform());
                if (locationList != null && locationList.size() != 0) {
                    for (int location : locationList) {
                        detailedEntity = getEntityByLocation(location);
                        if (detailedEntity != null) {
                            detailedEntity.setEntryMap(null);
                        }
                        adapter.notifyItemChanged(location);
                    }
                }
            }
        } else if ("plugin".equals(status.getStatus())) {
            handler.postDelayed(initPluginRunnable, 100);
        }
    }

    Runnable initPluginRunnable = new Runnable() {
        @Override
        public void run() {
            if (PackageManager.getPluggableSize() != 0
                    && adapter.getPluginList().isEmpty()) {
                if (adapter.isInitPlugin()) {
                    adapter.initPlugin();
                } else {
                    handler.postDelayed(initPluginRunnable, 100);
                }
            }
        }
    };

    //安装、卸载事件
    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);
                    }
                }
            }
        }
        //特殊 插件化
        name = adapter.getPluginNameMap().get(busFour.getPackageName());
        if (name != null) {
            ArrayList<Integer> locationList = adapter.getLocationMap().get(name);
            if (locationList != null && locationList.size() != 0) {
                int location;
                for (int i = 0; i < locationList.size(); i++) {
                    location = locationList.get(i);
                    if ("安装".equals(busFour.getType()) || "卸载".equals(busFour.getType())) {
                        List<GameEntity> list = adapter.getPluginList();
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getApk().get(0).getPackageName()
                                    .equals(busFour.getPackageName())) {
                                list.remove(j);
                                adapter.notifyItemRemoved(location);
                                locationList.remove(i);
                                break;
                            }
                        }
                    }
                }
                if (locationList.isEmpty()) {
                    adapter.getLocationMap().remove(name);
                }
            }
        }
    }

    //连接上网络事件
    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);
            } else if (adapter.isNetworkError()) {
                adapter.setNetworkError(false);
                adapter.notifyItemChanged(adapter.getItemCount() - 1);
                adapter.load();
            }
        }
    }

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

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

    private GameEntity getEntityByLocation(int position) {
        List<GameEntity> pluginList = adapter.getPluginList();
        List<SubjectEntity> subjectList = adapter.getSubjectList();

        if (!pluginList.isEmpty() && position > 1 && position <= 1 + pluginList.size()) {
            return pluginList.get(position - 2);
        }

        int offset = 1;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                return subjectList.get(i).getData().get(position - offset - 1);
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }

        return null;
    }

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

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

    public boolean isEverpause() {
        return isEverpause;
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isDestroy) {
                adapter = new Game1FragmentAdapter(Game1Fragment.this, fm_game_swipe_refresh, 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;
    }
}
