package com.uiui.zyappstore.adapter;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.IEntity;
import com.arialyy.aria.core.task.DownloadTask;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uiui.zyappstore.R;
import com.uiui.zyappstore.bean.GlideCircleWithBorder;
import com.uiui.zyappstore.utils.FileUtils;
import com.uiui.zyappstore.view.NumberProgressBar;

import java.util.List;


public class DownloadManagerAdapter extends RecyclerView.Adapter<DownloadManagerAdapter.Holder> {

    public static final int TYPE_ALL = 0;
    public static final int TYPE_FINISH = 1;
    public static final int TYPE_ING = 2;

    private Context mContext;
    private List<DownloadEntity> mEntityList;
    private DownloadTask mDownloadTask;

    private final LayoutInflater mInflater;
    private Handler mhandler;

    public DownloadManagerAdapter(Context context, Handler handler) {
        this.mContext = context;
        mInflater = LayoutInflater.from(mContext);
        this.mhandler = handler;
    }


//    public void updateData(int type) {
//        //这里是将数据库的数据恢复
//        this.type = type;
//        if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll());
//        if (type == TYPE_FINISH)
//            values = OkDownload.restore(DownloadManager.getInstance().getFinished());
//        if (type == TYPE_ING)
//            values = OkDownload.restore(DownloadManager.getInstance().getDownloading());
//        notifyDataSetChanged();
//    }

    public void updateNotCompleteTask() {
        mEntityList = Aria.download(this).getAllNotCompleteTask();
        notifyDataSetChanged();
    }

    public void setData(List<DownloadEntity> list) {
        this.mEntityList = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new Holder(mInflater.inflate(R.layout.item_download_manager, parent, false));

    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        Aria.download(this).register();
        final DownloadEntity entity = mEntityList.get(position);
//        DownloadTask task = values.get(position);
//        String tag = createTag(task);
//        task.register(new ListDownloadListener(tag, holder))//
//                .register(new LogDownloadListener());
//        holder.setTag(tag);
//        holder.setTask(task);
//        holder.bind();
//        holder.refresh(task.progress);
        JsonObject jsonObject = JsonParser.parseString(Aria.download(this).load(entity.getId()).getExtendField()).getAsJsonObject();

        Glide.with(mContext)
                .asBitmap()
                .load(jsonObject.get("app_img").getAsString())
//                    .placeholder(R.drawable.ic_place_holder)
                .transform(new GlideCircleWithBorder(mContext))
                .into(holder.icon);
        holder.name.setText(jsonObject.get("app_name").getAsString());
        holder.pbProgress.setMax(100);
        holder.pbProgress.setProgress(entity.getPercent());
        long progress = entity.getCurrentProgress();
        holder.downloadSize.setText(FileUtils.formatFileSize(progress) + "/" + FileUtils.formatFileSize(entity.getFileSize()));
        holder.refreshEntity(entity);
        holder.start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (entity.getState()) {
                    case IEntity.STATE_OTHER:
                    case IEntity.STATE_FAIL:
                    case IEntity.STATE_STOP:
                    case IEntity.STATE_WAIT:
                    case IEntity.STATE_CANCEL:
                        Aria.download(this).load(entity.getId()).resume();
                        break;
                    case IEntity.STATE_RUNNING:
                        Aria.download(this).load(entity.getId()).stop();
                        break;
                    case IEntity.STATE_PRE:
                        break;
                    case IEntity.STATE_POST_PRE:
                        break;
                    case IEntity.STATE_COMPLETE:
                        break;
                    default:
                }
            }
        });
        if (null != mDownloadTask && mDownloadTask.getEntity().getUrl().equals(entity.getUrl())) {
            holder.refresh(mDownloadTask);
        }
        holder.remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Aria.download(this).load(entity.getId()).cancel(true);
            }
        });
    }

//    public void unRegister() {
//        Map<String, DownloadTask> taskMap = OkDownload.getInstance().getTaskMap();
//        for (DownloadTask task : taskMap.values()) {
//            task.unRegister(createTag(task));
//        }
//    }

//    private String createTag(DownloadTask task) {
//        return type + "_" + task.progress.tag;
//    }

    @Override
    public int getItemCount() {
        return null == mEntityList ? 0 : mEntityList.size();
    }

    public class Holder extends RecyclerView.ViewHolder {
        ImageView icon, remove;
        TextView name, state, downloadSize;
        Button start;
        NumberProgressBar pbProgress;

        //        private DownloadTask task;
        private String tag;

        Holder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            remove = itemView.findViewById(R.id.remove);
            name = itemView.findViewById(R.id.name);
            state = itemView.findViewById(R.id.state);
            downloadSize = itemView.findViewById(R.id.downloadSize);
            start = itemView.findViewById(R.id.start);
            pbProgress = itemView.findViewById(R.id.pbProgress);
        }


        void refresh(DownloadTask task) {
            switch (task.getState()) {
                case IEntity.STATE_OTHER:
                    start.setText("下载");
                    state.setText("未知");
                    break;
                case IEntity.STATE_FAIL:
                    start.setText("下载");
                    state.setText("出错");
                    break;
                case IEntity.STATE_COMPLETE:
                    start.setText("安装中");
                    state.setText("完成");
                    break;
                case IEntity.STATE_STOP:
                    start.setText("继续");
                    state.setText("停止");
                    break;
                case IEntity.STATE_WAIT:
                    start.setText("等待");
                    state.setText("等待");
                    break;
                case IEntity.STATE_RUNNING:
                    start.setText(task.getPercent() + "%");
                    pbProgress.setProgress(task.getPercent());
                    state.setText(task.getConvertSpeed());
                    long progress = task.getCurrentProgress();
                    downloadSize.setText(FileUtils.formatFileSize(progress) + "/" + task.getConvertFileSize());
                    break;
                case IEntity.STATE_PRE:
                    break;
                case IEntity.STATE_POST_PRE:
                    break;
                case IEntity.STATE_CANCEL:
                    break;
            }
        }

        void refreshEntity(DownloadEntity entity) {
            switch (entity.getState()) {
                case IEntity.STATE_OTHER:
                    start.setText("下载");
                    state.setText("未知");
                    break;
                case IEntity.STATE_FAIL:
                    start.setText("下载");
                    state.setText("出错");
                    break;
                case IEntity.STATE_COMPLETE:
                    start.setText("安装中");
                    state.setText("完成");
                    break;
                case IEntity.STATE_STOP:
                    start.setText("继续");
                    state.setText("停止");
                    break;
                case IEntity.STATE_WAIT:
                    start.setText("等待");
                    state.setText("等待");
                    break;
                case IEntity.STATE_RUNNING:
                    start.setText(entity.getPercent() + "%");
                    pbProgress.setProgress(entity.getPercent());
                    state.setText("下载中");
                    long progress = entity.getCurrentProgress();
                    downloadSize.setText(FileUtils.formatFileSize(progress) + "/" + entity.getConvertFileSize());
                    break;
                case IEntity.STATE_PRE:
                    break;
                case IEntity.STATE_POST_PRE:
                    break;
                case IEntity.STATE_CANCEL:
                    break;
            }
        }


//        public void setTask(DownloadTask task) {
//            this.task = task;
//        }

//        public void bind() {
//            Progress progress = task.progress;
//            AppInfo apk = (AppInfo) progress.extra1;
//            if (apk != null) {
//                Glide.with(mContext)
//                        .load(apk.getApp_img())
//                        .error(R.mipmap.ic_launcher)
//                        .transform(new GlideCircleWithBorder(mContext))
//                        .into(icon);
//                name.setText(apk.getApp_name());
//            } else {
//                name.setText(progress.fileName);
//            }
//            start.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    start();
//                }
//            });
//            remove.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    remove();
//                }
//            });
//
//        }

//        public void refresh(Progress progress) {
//            String currentSize = Formatter.formatFileSize(mContext, progress.currentSize);
//            String totalSize = Formatter.formatFileSize(mContext, progress.totalSize);
//            downloadSize.setText(currentSize + "/" + totalSize);
//            switch (progress.status) {
//                case Progress.NONE:
//                    state.setText("停止");
//                    start.setText("下载");
//                    break;
//                case Progress.PAUSE:
//                    state.setText("暂停中");
//                    start.setText("继续");
//                    break;
//                case Progress.ERROR:
//                    state.setText("下载出错");
//                    start.setText("出错");
//                    break;
//                case Progress.WAITING:
//                    state.setText("等待中");
//                    start.setText("等待");
//                    break;
//                case Progress.FINISH:
//                    state.setText("下载完成");
//                    start.setText("完成");
//                    break;
//                case Progress.LOADING:
//                    String speed = Formatter.formatFileSize(mContext, progress.speed);
//                    state.setText(String.format("%s/s", speed));
//                    start.setText("暂停");
//                    break;
//            }
//            pbProgress.setMax(10000);
//            pbProgress.setProgress((int) (progress.fraction * 10000));
//        }

//        public void start() {
//            Progress progress = task.progress;
//            switch (progress.status) {
//                case Progress.PAUSE:
//                case Progress.NONE:
//                case Progress.ERROR:
//                    task.start();
//                    break;
//                case Progress.LOADING:
//                    task.pause();
//                    break;
//                case Progress.FINISH:
//
//                    break;
//            }
//            refresh(progress);
//        }
//
//        public void remove() {
//            task.remove(true);
//            updateData(type);
//        }
//
//        public void restart() {
//            task.restart();
//        }
//
//        public void setTag(String tag) {
//            this.tag = tag;
//        }
//
//        public String getTag() {
//            return tag;
//        }
    }

    //    private class ListDownloadListener extends DownloadListener {
//
//        private Holder holder;
//
//        ListDownloadListener(Object tag, Holder holder) {
//            super(tag);
//            this.holder = holder;
//        }
//
//        @Override
//        public void onStart(Progress progress) {
//        }
//
//        @Override
//        public void onProgress(Progress progress) {
//            if (tag == holder.getTag()) {
//                holder.refresh(progress);
//            }
//        }
//
//        @Override
//        public void onError(Progress progress) {
//            Throwable throwable = progress.exception;
//            if (throwable != null) throwable.printStackTrace();
//        }
//
//        @Override
//        public void onFinish(File file, Progress progress) {
//            mhandler.sendEmptyMessage(100);
//        }
//
//        @Override
//        public void onRemove(Progress progress) {
//
//        }
//    }

    private void ItemChanged(DownloadTask task) {
        updateNotCompleteTask();
        mDownloadTask = task;
        notifyDataSetChanged();
        if (null == mEntityList) {
            return;
        }
        for (int i = 0; i < mEntityList.size(); i++) {
            if (mEntityList.get(i).getUrl().equals(task.getKey())) {
                notifyItemChanged(i);
            }
        }
    }

    @Download.onTaskRunning
    void onTaskRunning(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskComplete
    void onTaskComplete(DownloadTask task) {
        ItemChanged(task);
        updateNotCompleteTask();
    }

    @Download.onWait
    void onWait(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskStart
    void onTaskStart(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onPre
    void onPre(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskResume
    void onTaskResume(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskStop
    void onTaskStop(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskCancel
    void onTaskCancel(DownloadTask task) {
        ItemChanged(task);
    }

    @Download.onTaskFail
    void onTaskFail(DownloadTask task, Exception e) {
        ItemChanged(task);
    }
}
