package com.sheep.gamegroup.view.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.ImageView;
import android.widget.TextView;

import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.FindAppReservation;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
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 io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

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

/**
 * Created by realicing on 2018/5/10.
 * realicing@sina.com
 * 游戏预约
 */
public class ActReservation 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() {
        TitleBarUtils.getInstance()
                .setTitle(this, "游戏预约")
                .setTitleFinish(this);

        EventBus.getDefault().register(this);

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

        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(new AdbCommonRecycler<FindAppReservation>(SheepApp.getInstance(), list) {

            @Override
            public int getItemViewType(int position) {
                return position;
            }

            @Override
            public int getViewIdByType(int type) {//type来源于 getItemViewType 返回的值
                switch (type) {
                    case 0:
                        return R.layout.find_reservation_item_top;
                    default:
                        return R.layout.find_reservation_item_bottom;
                }
            }

            @Override
            public void convert(ViewHolder holder, FindAppReservation item) {
                View find_reservation_item_center = holder.itemView.findViewById(R.id.find_reservation_item_center);
                View find_reservation_item_bottom = holder.itemView.findViewById(R.id.find_reservation_item_bottom);
                if (find_reservation_item_bottom != null) {
                    find_reservation_item_center.setVisibility(item == null ? View.GONE : View.VISIBLE);
                    find_reservation_item_bottom.setVisibility(item == null ? View.VISIBLE : View.GONE);
                }
                if (item != null)
                    loadItem(holder.itemView, item);

            }
        });
    }

    private void loadItem(View itemView, final FindAppReservation item) {
        ImageView find_information_game_icon = (ImageView) itemView.findViewById(R.id.find_information_game_icon);
        TextView find_information_game_name = (TextView) itemView.findViewById(R.id.find_information_game_name);
        TextView find_information_game_time = (TextView) itemView.findViewById(R.id.find_information_game_time);
        TextView find_information_game_bt1 = (TextView) itemView.findViewById(R.id.find_information_game_bt1);
        final TextView find_information_game_bt2 = (TextView) itemView.findViewById(R.id.find_information_game_bt2);

        if (item != null && item.getApplication() != null) {
            final Applications findApp = item.getApplication();

            ViewUtil.setImage(find_information_game_icon, findApp.getIcon());
            ViewUtil.setText(find_information_game_name, findApp.getName());
            ViewUtil.setText(find_information_game_time, String.format(Locale.CHINA, "开放时间：\n%s", TimeUtil.TimeStamp2Date(findApp.getDownload_at(), "yyyy-MM-dd\u0020HH:mm")));
            if (findApp.isCanDownload()) {//可以下载
                downLoadTextViewMap.put(findApp.getDownload_link(), find_information_game_bt1);
                downLoadTextViewMap.put(findApp.getPackage_name(), find_information_game_bt1);
                findAppMap.put(findApp.getDownload_link(), findApp);
                findAppMap.put(findApp.getPackage_name(), findApp);
                findApp.getFindAppHelper().updateDownloadTaskView(this, findApp, find_information_game_bt1);
                find_information_game_bt2.setEnabled(false);
            } else {
                find_information_game_bt1.setEnabled(false);
                find_information_game_bt1.setText("即将开始");

                find_information_game_bt2.setEnabled(true);
                find_information_game_bt2.setText(item.isCancel() ? "立即预约" : "取消预约");
                find_information_game_bt2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        find_information_game_bt2.setEnabled(false);
                        if (item.isCancel()) {//已经取消预约则进行预约
                            recordAppDownloads(find_information_game_bt2, findApp.getId(), item);
                        } else {//取消预约
                            deleteDownloads(find_information_game_bt2, item);
                        }
                    }
                });
            }
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Jump2View.getInstance().goFindGame(ActReservation.this, findApp);
                }
            });
        } else {

            ViewUtil.setText(find_information_game_name);
            ViewUtil.setText(find_information_game_time);
            find_information_game_bt1.setEnabled(false);
            find_information_game_bt2.setEnabled(false);
        }
    }

    //预约下载
    private void recordAppDownloads(final TextView find_information_game_bt2, int id, final FindAppReservation item) {
        SheepApp.getInstance().getNetComponent().getApiService().recordAppDownloads(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        find_information_game_bt2.setEnabled(true);
                        find_information_game_bt2.setText("取消预约");
                        item.setCancel(false);
                        G.showToast("预约成功");
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast("预约失败");
                        find_information_game_bt2.setEnabled(true);
                    }
                });
    }

    //取消预约
    private void deleteDownloads(final TextView find_information_game_bt2, final FindAppReservation item) {
        SheepApp.getInstance().getNetComponent().getApiService().deleteDownloads(item.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        find_information_game_bt2.setEnabled(true);
                        find_information_game_bt2.setText("立即预约");
                        item.setCancel(true);
                        G.showToast("取消预约成功");
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast("取消预约失败");
                        find_information_game_bt2.setEnabled(true);
                    }
                });
    }

    @Override
    public void initListener() {

    }

    private List<FindAppReservation> list = ListUtil.emptyList();

    @Override
    public void initData() {
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(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<FindAppReservation> newList = baseMessage.getDataList(FindAppReservation.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() {
        if (empty_view == null) {
            return;
        }
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        refresh.setRefreshing(false);
        view_list.getAdapter().notifyDataSetChanged();
    }

    private Map<String, Applications> findAppMap = new HashMap<>();

    //获取任务对应的findApp
    private Applications getFindAppByKey(String key) {
        if (findAppMap.containsKey(key))
            return findAppMap.get(key);
        return null;
    }

    private Map<String, TextView> downLoadTextViewMap = new HashMap<>();

    //获取任务对应的TextView来更新进度
    private TextView getTextViewByTask(DownLoadInfo task) {
        return getTextViewByKey(task.getMDownloadUrl());
    }

    private TextView getTextViewByKey(String key) {
        if (downLoadTextViewMap.containsKey(key))
            return downLoadTextViewMap.get(key);
        return null;
    }

    //下载状态监听
    void onPre(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("准备下载中");
        }
    }

    void taskStart(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("开始下载中");
        }
    }

    void taskResume(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("恢复下载中");
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    protected void running(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(String.format(Locale.CHINA, "%d%%(%s)", Math.abs(task.getMPercent()), task.getAverageSpeed()));//添加下载速度
        }
    }

    void taskStop(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

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

    void taskFail(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    void taskComplete(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.START_INSTALL);
        }
        Applications findApp = getFindAppByKey(task.getMDownloadUrl());
        if (findApp != null) {
            findApp.updateState(DownloadUtil.STATUS_FINISH);
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        if (event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            switch (event.getEventTypes()) {
                case DOWNLOAD_RUNNING:
                    running(task);
                    break;
                case DOWNLOAD_STOP:
                    taskStop(task);
                    break;
                case DOWNLOAD_COMPLETE:
                    taskComplete(task);
                    break;
                case DOWNLOAD_CANCEL:
                    taskCancel(task);
                    break;
                case DOWNLOAD_FAIL:
                    taskFail(task);
                    break;
            }
        }
    }

    @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:", "");

            Applications findApp = getFindAppByKey(packageName);
            TextView textView = getTextViewByKey(packageName);
            if (findApp != null) {
                switch (intent.getAction()) {
                    case ACTION_PACKAGE_ADDED:
                        if (textView != null) {
                            textView.setText(CommonUtil.GAME_OPEN);
                        }
                        findApp.updateState(DownloadUtil.STATUS_INSTALLED);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName, findApp.getDownload_url());
                        if (TextUtils.isEmpty(path)) {
                            findApp.updateState(DownloadUtil.STATUS_INIT);
                            if (textView != null) {
                                textView.setText(CommonUtil.START_DOWNLOAD);
                            }
                        } else {
                            findApp.updateState(DownloadUtil.STATUS_FINISH);
                            if (textView != null) {
                                textView.setText(CommonUtil.START_INSTALL);
                            }
                        }
                        break;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
