package com.tofly.ghrq_route.common.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.lcp.arecyclerview.widget.ARecyclerBaseAdapter;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.common.ui.dialog.DownloadListDialog;
import com.tofly.ghrq_route.module.download.controller.DownloadResultCallback;
import com.tofly.ghrq_route.module.download.controller.OnDownloadListItemClickListener;
import com.tofly.ghrq_route.module.download.domain.DownloadData;
import com.tofly.ghrq_route.module.download.service.DownloadService;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.common.util.TextUtilOfPatrol;
import com.tofly.ghrq_route.common.util.file.FileUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by lihualong on 2017/6/19.
 */

public class DownloadListAdapter extends ARecyclerBaseAdapter {
    private String zero;
    private String one;
    private String two;
    private String three;
    private final String PLEASE_DOWNLOAD = "请点击下载";
    private final String NO_UPDATE = "下载完成";
    private final String PLEASE_UPDATE = "请点击更新";
    private final String SERVICE_NO_DATA = "服务器暂无数据";
    private boolean canDownload;
    private OnDownloadListItemClickListener downloadClickListener;
    private final DBDaoHelper daoHelper;

    public DownloadListAdapter(Context context, List<DownloadData> list) {
        super(context, list);
        zero = context.getString(R.string.map_list_status_zero);
        one = context.getString(R.string.map_list_status_one);
        two = context.getString(R.string.map_list_status_two);
        three = context.getString(R.string.map_list_status_three);
        daoHelper = DBDaoHelper.getInstance();

    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(this.mContext).inflate(R.layout.item_download_list, null);
        return new ViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((ViewHolder) holder).setData(position);
    }

    public void setOnDownloadClickListener(OnDownloadListItemClickListener onDownloadClickListener) {
        downloadClickListener = onDownloadClickListener;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.caption)
        TextView caption;
        @BindView(R.id.type)
        TextView type;
        @BindView(R.id.size)
        TextView size;
        @BindView(R.id.release_time)
        TextView releaseTime;
        @BindView(R.id.doanlowd_time)
        TextView doanlowdTime;
        @BindView(R.id.state)
        TextView state;
        @BindView(R.id.deal)
        TextView deal;
        private DownloadListOnClickListener downloadListOnClickListener;
        private boolean canDownload = false;
        private DownloadResultCallback downloadResultCallback;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        void setData(int position) {
            DownloadData downloadData = (DownloadData) mList.get(position);
            int nameSize = BaseApp.dip2px(16);
            int headerSize = BaseApp.dip2px(15);
            int contentSize = BaseApp.dip2px(14);
            String dataname = "管网名称：" + downloadData.getName();
            caption.setText(TextUtilOfPatrol.toTurnStyle(dataname, nameSize, headerSize, TextUtilOfPatrol
                    .NAME_HEAD, TextUtilOfPatrol.NAME_CONTENT));
            String ss = "";
            String[] aar = downloadData.getCval().split(".");
            if (aar.length > 1) {
                ss = aar[1];
            }
            String datatype = "类型：" + ss;
            type.setText(TextUtilOfPatrol.toTurnStyle(datatype, headerSize, contentSize, TextUtilOfPatrol.NAME_HEAD,
                    TextUtilOfPatrol.NAME_CONTENT));
//            long datasize = downloadData.getDatasize();
//            String[] fileSize = FileUtil.fileSize(datasize);
//            String text = "大小：" + fileSize[0] + fileSize[1];
            if (!TextUtils.isEmpty(downloadData.getDatasize())) {
                size.setText(TextUtilOfPatrol.toTurnStyle("大小：" + downloadData.getDatasize(), headerSize, contentSize, TextUtilOfPatrol.NAME_HEAD,
                        TextUtilOfPatrol.NAME_CONTENT));
            } else {
                size.setVisibility(View.GONE);
            }
            String updatetime;
            if (!TextUtils.isEmpty(downloadData.getUpdatetime())) {
                updatetime = downloadData.getUpdatetime();
            } else {
                updatetime = downloadData.getCreateTime();
            }
            String displayUpdateTime = "更新时间：" + updatetime;
            releaseTime.setText(TextUtilOfPatrol.toTurnStyle(displayUpdateTime, headerSize, contentSize, TextUtilOfPatrol
                    .NAME_HEAD, TextUtilOfPatrol.NAME_CONTENT));
            String downloadtime = downloadData.getDownloadTime();
            if (TextUtils.isEmpty(downloadtime)) {
                downloadtime = " ";
            }
            String displayDownloadTime = "下载时间：" + downloadtime;
            doanlowdTime.setText(TextUtilOfPatrol.toTurnStyle(displayDownloadTime, headerSize, contentSize, TextUtilOfPatrol
                    .NAME_HEAD, TextUtilOfPatrol.NAME_CONTENT));
            String status = String.valueOf(downloadData.getDownload_state());
            //            显示在地图在服务器中的状态
            if (zero.equals(status)) {
                state.setText(R.string.map_list_status_genetating);
            } else if (one.equals(status)) {
                state.setText(R.string.map_list_updating);
            } else if (two.equals(status)) {
                state.setText(R.string.map_list_status_updated);
                state.setTextColor(TextUtilOfPatrol.NAME_CONTENT);
            } else if (three.equals(status)) {
                state.setText(R.string.map_list_status_unuse);
            } else {
                state.setText(R.string.map_list_status_unknow);
            }

//            boolean serviceStarted = AppUtil.isServiceStarted(mContext, DownloadService.class.getName());


//            是否存在并设置下载
            final String filename = downloadData.getCval();
            String filePath = C.dir.data + filename;
            File file = new File(filePath);
            final Resources resources = mContext.getResources();
            if (!file.exists()) {
                if (two.equals(status)) {
                    canDownload = true;
                    canDownData(PLEASE_DOWNLOAD, filename, resources, downloadData.getId());
                } else {
                    canDownload = false;
                    deal.setText(SERVICE_NO_DATA);
                    deal.setEnabled(false);
                    deal.setTextColor(TextUtilOfPatrol.NAME_CONTENT);
                    if (status.equals(one)) {
                        DBDaoHelper.getInstance().asyDownloadData(downloadData);
                    }
                }
            } else {
                int downloadByMapId = daoHelper.isDownloadByMapId(downloadData.getId());
                if (downloadByMapId == 4) {
                    deal.setText("正在下载");
                    canDownload = false;
                    deal.setTextColor(TextUtilOfPatrol.DOWNLOADING);
                } else if (downloadByMapId == 2) {
                    deal.setText("下载失败,稍后再试");
                    deal.setTextColor(TextUtilOfPatrol.CAN_DOWNLOAD);
                    canDownload = true;
                } else {
                    if (downloadByMapId == 1) {
                        deal.setText("已下载");
                        deal.setTextColor(TextUtilOfPatrol.NAME_CONTENT);
                        canDownload = false;
                    }
                    boolean timeDifferent = FileUtil.getTimeDifferent(updatetime, downloadtime);
                    if (!timeDifferent || zero.equals(status) || one.equals(status) || three.equals
                            (status)) {
                        canDownload = false;
                        deal.setEnabled(false);
                        deal.setText(NO_UPDATE);
                        deal.setTextColor(TextUtilOfPatrol.NAME_CONTENT);
                    } else if (two.equals(status)) {
                        canDownload = true;
                        deal.setEnabled(true);
                        deal.setText(PLEASE_UPDATE);
                        deal.setTextColor(TextUtilOfPatrol.DOWNLOADING);
                        canDownData(PLEASE_UPDATE, filename, resources, downloadData.getId());
                    }
                }

            }
            if (downloadListOnClickListener == null) {
                downloadListOnClickListener = new DownloadListOnClickListener(deal, position,
                        downloadData, canDownload);
            } else {
                downloadListOnClickListener.updateData(position, downloadData, canDownload);
            }
            this.itemView.setOnClickListener(view -> {
                if (downloadListOnClickListener != null) {
                    downloadListOnClickListener.onClick(view);
                }
            });
        }


        private class DownloadListOnClickListener implements View.OnClickListener {
            private int position;
            private DownloadData downloadData;
            private boolean canDownload;
            private TextView deal;

            public DownloadListOnClickListener(TextView deal, int position, DownloadData downloadData, boolean canDownload) {
                this.position = position;
                this.downloadData = downloadData;
                this.canDownload = canDownload;
                this.deal = deal;
            }

            @Override
            public void onClick(View v) {
                downloadResultCallback = () -> {
                    Intent service = new Intent(mContext, DownloadService.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(DownloadListDialog.FILENAME, downloadData.getCval());
                    String id = downloadData.getId();
                    bundle.putString(DownloadListDialog.ID, id);
                    bundle.putInt(DownloadListDialog.POSITION, position);
                    service.putExtras(bundle);
                    mContext.startService(service);
                    deal.setText("正在下载");
                    deal.setTextColor(TextUtilOfPatrol.DOWNLOADING);
                    daoHelper.updatePipeDbState(id, 4);
                    canDownload = false;
                    ViewHolder.this.canDownload = false;
                };
                DownloadListAdapter.this.downloadClickListener.onItemClick(canDownload, v, position, downloadData, downloadResultCallback);
            }

            public void updateData(int position, DownloadData downloadData, boolean canDownload) {
                this.position = position;
                this.downloadData = downloadData;
                this.canDownload = canDownload;
            }


        }

        private void canDownData(final String msg, final String filename, Resources resources, final String _id) {
            deal.setText(msg);
            deal.setTextColor(TextUtilOfPatrol.CAN_DOWNLOAD);
            deal.setEnabled(true);

        }
    }

}
