package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.android.view.tag.FlowLayout;
import com.kfzs.android.view.tag.TagAdapter;
import com.kfzs.android.view.tag.TagFlowLayout;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.Article;
import com.sheep.gamegroup.model.entity.ArticleTag;
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.TestUtil;
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.PackageUtil;

import org.afinal.simplecache.ApiKey;
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 io.reactivex.Observable;

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

/**
 * Created by realicing on 2018/9/7.
 * realicing@sina.com
 */
public class FgtFindChild extends BaseListFragment2<Article> {
    @Override
    protected RecyclerView.Adapter getAdapter() {
        return new CommonRecycler(list);
    }

    @Override
    protected String getKey(int page, int per_page) {
        return ApiKey.articles(page, per_page, type);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.getFindList(page, per_page, type);
    }

    @Override
    protected Class<Article> getTClass() {
        return Article.class;
    }

    private int type;

    public static FgtFindChild newInstance(int type) {
        FgtFindChild fgt = new FgtFindChild();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fgt.setArguments(bundle);
        return fgt;
    }

    /**
     * 点击一个发现元素
     *
     * @param item
     */
    private void onClickItem(Article item) {
        if (item != null) {
            Jump2View.getInstance().goFindItem(activity, item);
        }
    }


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

    //更新按钮状态与添加点击事件
    private void updateView(Activity activity, Applications findApp, TextView textView) {
        if (findApp.isCanDownload()) {//可下载
            downLoadTextViewMap.put(findApp.getDownload_link(), textView);
            downLoadTextViewMap.put(findApp.getPackage_name(), textView);
            findAppMap.put(findApp.getDownload_link(), findApp);
            findAppMap.put(findApp.getPackage_name(), findApp);
            findApp.getFindAppHelper().updateDownloadTaskView(activity, findApp, textView);
        } else {//预约下载
            findApp.getFindAppHelper().updateReservationView(activity, findApp, textView);
        }
    }

    //下载状态监听
    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%%", Math.abs(task.getMPercent())));
        }
    }

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

    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @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;
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type", 0);
        }
        EventBus.getDefault().register(this);
    }

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

    @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;
                }
            }
        }
    }

    private class CommonRecycler extends AdbCommonRecycler<Article> {

        private Converter commonConverter, newsConverter;

        public CommonRecycler(List<Article> list) {
            super(SheepApp.getInstance(), list);
            commonConverter = new CommonConverter();
            if(!TestUtil.isLTVersion3_4_5())
                newsConverter = new NewsConverter();
        }

        @Override
        public int getItemViewType(int position) {
            Article article = list.get(position);
            return article.getType();
        }

        @Override
        public int getViewIdByType(int type) {//type来源于 getItemViewType 返回的值
            if (type == 2 && newsConverter != null) {
                return R.layout.find_item_news;
            }
            return R.layout.find_item;
        }

        @Override
        public void convert(final ViewHolder holder, final Article item) {
            if (item == null) {
                return;
            }
            if (item.getType() == 2 && newsConverter != null) {
                newsConverter.convert(holder, item);
            } else {
                commonConverter.convert(holder, item);
            }
        }
    }

    private class CommonConverter implements AdbCommonRecycler.Converter {

        @Override
        public void convert(final ViewHolder holder, final Article item) {
            View rootConvertView = holder.itemView;
            View padding = rootConvertView.findViewById(R.id.padding);
            if (padding == null) {
                return;
            }
            padding.setVisibility(holder.getAdapterPosition() == 1 ? View.GONE : View.VISIBLE);
            TextView find_item_name = (TextView) rootConvertView.findViewById(R.id.find_item_name);
            TextView find_item_time = (TextView) rootConvertView.findViewById(R.id.find_item_time);
            ImageView find_item_iv = (ImageView) rootConvertView.findViewById(R.id.find_item_iv);
            TextView find_item_des = (TextView) rootConvertView.findViewById(R.id.find_item_des);
            TextView find_item_download = (TextView) rootConvertView.findViewById(R.id.find_item_download);
            TagFlowLayout find_item_tags = (TagFlowLayout) rootConvertView.findViewById(R.id.find_item_tags);

            if (item.isGame()) {
                find_item_download.setVisibility(View.VISIBLE);
                Applications findApp = item.getApplication();
                updateView(activity, findApp, find_item_download);
            } else {
                find_item_download.setVisibility(View.GONE);
            }
            ViewUtil.setText(find_item_name, item.getTitle());
            ViewUtil.setTextTime(find_item_time, item.getCreated_at(), "yyyy-MM-dd");
            ViewUtil.setImage(find_item_iv, item.getPictures());
            ViewUtil.setText(find_item_des, item.getDes());
            item.removeNullTag();
            if (ListUtil.isEmpty(item.getTages())) {
                find_item_tags.setVisibility(View.GONE);
            } else {
                find_item_tags.setVisibility(View.VISIBLE);
                TagAdapter adapter = new TagAdapter<ArticleTag>(item.getTages()) {
                    @Override
                    public View getView(FlowLayout parent, int position, ArticleTag item) {
                        TextView tv = (TextView) LayoutInflater.from(activity).inflate(R.layout.find_item_tag, parent, false);
                        ViewUtil.setText(tv, item.getName());
                        return tv;
                    }
                };
                find_item_tags.setAdapter(adapter);
            }
            rootConvertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickItem(item);
                }
            });
        }
    }

    private class NewsConverter implements AdbCommonRecycler.Converter {

        @Override
        public void convert(ViewHolder holder, final Article item) {
            View rootConvertView = holder.itemView;
            TextView find_item_name = rootConvertView.findViewById(R.id.find_item_name);
            TextView find_item_time = rootConvertView.findViewById(R.id.find_item_time);
            ImageView find_item_iv = rootConvertView.findViewById(R.id.find_item_iv);
            ViewUtil.setText(find_item_name, item.getTitle());
            ViewUtil.setTextTime(find_item_time, item.getCreated_at(), "yyyy-MM-dd");
            ViewUtil.setImage(find_item_iv, item.getPictures());
            rootConvertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickItem(item);
                }
            });
        }
    }

}
