package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
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.TextView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FindApp;
import com.sheep.gamegroup.model.entity.Welfare;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.view.adapter.DownloadWelfareAdapter;
import com.sheep.gamegroup.view.adapter.GiftCenterAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.content.Intent.ACTION_PACKAGE_ADDED;
import static android.content.Intent.ACTION_PACKAGE_REMOVED;

/**
 * 福利中心--点击全部礼包  进入  礼包中心
 * Created by realicing on 2018/8/28.
 * realicing@sina.com
 */
public class ActGiftCenter extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.net_empty_fresh_list_not_wrap;
    }

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.view_list)
    RecyclerView view_list;

    @Override
    public void initView() {
        activity = this;
        TitleBarUtils.getInstance()
                .setTitle(this, "礼包中心")
                .setTitleFinish(this);

        EventBus.getDefault().register(this);
        Aria.download(this).register();

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
                refresh.setRefreshing(false);
            }
        });

        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(new GiftCenterAdapter(activity, list));
    }

    private Activity activity;
    private List<Welfare> list = ListUtil.emptyList();
    @Override
    public void initListener() {

    }


    @Override
    public void initData() {
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(Integer result) {
                if (result != 0) {//无网络
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
            }
        });
        SheepApp.getInstance().getNetComponent().getApiService().getFindAppReservationList(1, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<Welfare> newList = baseMessage.getDataList(Welfare.class);
                        list.clear();
                        ListUtil.addAll(list, newList);
                        if(!list.isEmpty())
                            list.add(null);//底部圆角
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        list.clear();
                        notifyDataSetChanged();
                    }
                });
    }


    private void notifyDataSetChanged() {
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        refresh.setRefreshing(false);
        view_list.getAdapter().notifyDataSetChanged();
    }

    private Map<String, FindApp> findAppMap = new HashMap<>();
    //获取任务对应的findApp
    private FindApp getFindAppByKey(String key) {
        if(findAppMap.containsKey(key))
            return findAppMap.get(key);
        return null;
    }
    private Map<String, TextView> downLoadTextViewMap = new HashMap<>();
    //获取任务对应的TextView来更新进度
    private TextView getTextViewByTask(DownloadTask task) {
        return getTextViewByKey(task.getKey());
    }
    private TextView getTextViewByKey(String key) {
        if(downLoadTextViewMap.containsKey(key))
            return downLoadTextViewMap.get(key);
        return null;
    }
    //下载状态监听

    @Download.onPre void onPre(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("准备下载中");
        }
    }

    @Download.onTaskStart void taskStart(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("开始下载中");
        }
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("恢复下载中");
        }
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(String.format(Locale.CHINA, "%d%%", Math.abs(task.getPercent())));
        }
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("已经取消");
        }
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.START_INSTALL);
        }
        FindApp findApp = getFindAppByKey(task.getKey());
        if(findApp != null) {
            findApp.updateState(DownloadTaskService.STATUS_FINISH);
        }
    }

    @Subscribe
    public void onEventMainThread(Intent intent) {
        if(intent != null && intent.getAction() != null && intent.getDataString() != null && intent.getDataString().contains("package:")){
            String packageName = intent.getDataString().replace("package:","");

            TextView textView = getTextViewByKey(packageName);
            if(textView != null) {
                switch (intent.getAction()){
                    case ACTION_PACKAGE_ADDED:
                        textView.setText(CommonUtil.GAME_OPEN);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName);
                        if(TextUtils.isEmpty(path)) {
                            textView.setText(CommonUtil.START_DOWNLOAD);
                        } else {
                            textView.setText(CommonUtil.START_INSTALL);
                        }
                        break;
                }
            }
            FindApp findApp = getFindAppByKey(packageName);
            if(findApp != null) {
                switch (intent.getAction()){
                    case ACTION_PACKAGE_ADDED:
                        findApp.updateState(DownloadTaskService.STATUS_INSTALLED);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName);
                        if(TextUtils.isEmpty(path)) {
                            findApp.updateState(DownloadTaskService.STATUS_INIT);
                        } else {
                            findApp.updateState(DownloadTaskService.STATUS_FINISH);
                        }
                        break;
                }
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
