package com.uiui.zyappstore.adapter;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

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.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uiui.zyappstore.R;
import com.uiui.zyappstore.activity.DetailsActivity;
import com.uiui.zyappstore.bean.AppInfo;
import com.uiui.zyappstore.bean.GlideCircleWithBorder;
import com.uiui.zyappstore.utils.ApkUtils;
import com.uiui.zyappstore.utils.FileUtils;
import com.uiui.zyappstore.utils.StorageUtils;
import com.uiui.zyappstore.utils.ToastUtil;
import com.uiui.zyappstore.utils.Utils;

import org.jetbrains.annotations.NotNull;

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

/**
 * Created by asus on 2017/10/23.
 */

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.Holder> {
    private static final String TAG = AppAdapter.class.getSimpleName();

    private Context mContext;
    private List<AppInfo> mAppInfoList;
    private DownloadTask mDownloadTask;
    private boolean mShowLine = true;

    public AppAdapter(Context context) {
        this.mContext = context;
    }

    @NotNull
    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        return new Holder(LayoutInflater.from(context).inflate(R.layout.item_app, parent, false));
    }

    @Override
    public void onBindViewHolder(final Holder holder, final int position) {
        Aria.download(this).register();
        final AppInfo appInfo = mAppInfoList.get(position);
//        ImageLoader.getDefault().loadUrlRound(mContext, appInfo.getApp_img(), holder.ivIcon);

        Glide.with(mContext)
                .asBitmap()
                .load(appInfo.getApp_img())
                .error(R.mipmap.ic_launcher)
//                    .placeholder(R.drawable.ic_place_holder)
                .transform(new GlideCircleWithBorder(mContext))
                .into(holder.ivIcon);
        holder.tvCompany.setText(appInfo.getApp_developer());
        holder.tvName.setText(appInfo.getApp_name());
        holder.tvSize.setText(StorageUtils.byteToMB(appInfo.getApp_size()));
        holder.ratingBar.setRating((float) appInfo.getApp_score());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DetailActivity.startDetailActivity(mContext, appInfo);
                Intent intent = new Intent(mContext, DetailsActivity.class);
                intent.putExtra("appinfo", appInfo);
                mContext.startActivity(intent);
            }
        });
        if (mShowLine) {
            if (getItemCount() % 2 == 0) {
                if (getItemCount() - 1 == position || getItemCount() - 2 == position) {
                    holder.mView.setVisibility(View.GONE);
                } else {
                    holder.mView.setVisibility(View.VISIBLE);
                }
            } else {
                if (getItemCount() - 1 == position) {
                    holder.mView.setVisibility(View.GONE);
                } else {
                    holder.mView.setVisibility(View.VISIBLE);
                }
            }
        } else {
            holder.mView.setVisibility(View.GONE);
        }
        final boolean installed = ApkUtils.isInstalled(mContext, appInfo.getApp_package());
        final boolean update = ApkUtils.isUpdate(mContext, appInfo.getApp_package(), appInfo.getApp_version_code());
        if (installed) {
            if (update) {
                holder.btnDownLoad.setText("更新");
                holder.btnDownLoad.setTextColor(mContext.getColor(R.color.default_text_color));
                holder.btnDownLoad.setBackground(mContext.getDrawable(R.drawable.btn_shap_download));
            } else {
                holder.btnDownLoad.setText("打开");
                holder.btnDownLoad.setTextColor(mContext.getColor(R.color.white));
                holder.btnDownLoad.setBackground(mContext.getDrawable(R.drawable.btn_shap_open));
            }
        } else {
            holder.btnDownLoad.setText("安装");
            holder.btnDownLoad.setTextColor(mContext.getColor(R.color.default_text_color));
            holder.btnDownLoad.setBackground(mContext.getDrawable(R.drawable.btn_shap_download));
            if (null != mDownloadTask) {
                if (mDownloadTask.getKey().equals(appInfo.getApp_url())) {
                    holder.refresh(mDownloadTask);
                }
            } else {
                DownloadEntity entity = Aria.download(this).getFirstDownloadEntity(appInfo.getApp_url());
                if (null != entity) {
                    holder.refreshEntity(entity);
                }
            }
        }
        holder.btnDownLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (installed && !update) {
                    ApkUtils.openApp(mContext, appInfo.getApp_package());
                } else {
                    int is_storeinstall = Settings.Global.getInt(mContext.getContentResolver(), "setting_is_storeinstall", 0);
                    Log.e(TAG, "onClick: " + is_storeinstall);
                    if (is_storeinstall == 0) {
                        ToastUtil.show("应用市场已被禁止安装");
                        return;
                    }
                    Utils.addPackageToWhiteList(mContext, appInfo.getApp_package());
                    DownloadEntity entity = Aria.download(this).getFirstDownloadEntity(appInfo.getApp_url());
                    if (null != entity) {
                        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:
                                File file = new File(entity.getFilePath());
                                if (file.exists()) {
                                    holder.btnDownLoad.setText("安装中");
                                    ApkUtils.installApp(mContext, entity.getFilePath());
                                } else {
                                    Aria.download(this).load(entity.getId()).cancel(true);
                                    JsonObject jsonObject = JsonParser.parseString(new Gson().toJson(appInfo)).getAsJsonObject();
                                    FileUtils.ariaDownload(mContext, appInfo.getApp_url(), jsonObject);
                                }

                                break;
                            default:
                        }
                    } else {
                        JsonObject jsonObject = JsonParser.parseString(new Gson().toJson(appInfo)).getAsJsonObject();
                        FileUtils.ariaDownload(mContext, appInfo.getApp_url(), jsonObject);
                    }
                }
            }
        });
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }


    public class Holder extends RecyclerView.ViewHolder {
        ImageView ivIcon;
        TextView tvCompany, tvName, tvSize;
        Button btnDownLoad;
        RatingBar ratingBar;
        View mView;

        public Holder(View itemView) {
            super(itemView);
            ivIcon = itemView.findViewById(R.id.app_iv_icon);
            tvCompany = itemView.findViewById(R.id.app_tv_company);
            tvName = itemView.findViewById(R.id.app_tv_name);
            tvSize = itemView.findViewById(R.id.app_tv_size);
            btnDownLoad = itemView.findViewById(R.id.app_btn_download);
            ratingBar = itemView.findViewById(R.id.app_rating_bar);
            mView = itemView.findViewById(R.id.line);
        }

        void refresh(DownloadTask task) {
            switch (task.getState()) {
                case IEntity.STATE_OTHER:
                    btnDownLoad.setText("安装");
                    break;
                case IEntity.STATE_FAIL:
                    btnDownLoad.setText("出错");
                    break;
                case IEntity.STATE_COMPLETE:
                    btnDownLoad.setText("安装");
                    break;
                case IEntity.STATE_STOP:
                    btnDownLoad.setText("继续");
                    break;
                case IEntity.STATE_WAIT:
                    btnDownLoad.setText("等待");
                    break;
                case IEntity.STATE_RUNNING:
                    btnDownLoad.setText(task.getPercent() + "%");
                    break;
                case IEntity.STATE_PRE:
                    break;
                case IEntity.STATE_POST_PRE:
                    break;
                case IEntity.STATE_CANCEL:
                    break;
                default:
            }
        }

        void refreshEntity(DownloadEntity entity) {
            switch (entity.getState()) {
                case IEntity.STATE_OTHER:
                    btnDownLoad.setText("安装");
                    break;
                case IEntity.STATE_FAIL:
                    btnDownLoad.setText("出错");
                    break;
                case IEntity.STATE_COMPLETE:
                    btnDownLoad.setText("安装");
                    break;
                case IEntity.STATE_STOP:
                    btnDownLoad.setText("继续");
                    break;
                case IEntity.STATE_WAIT:
                    btnDownLoad.setText("等待");
                    break;
                case IEntity.STATE_RUNNING:
                    btnDownLoad.setText(entity.getPercent() + "%");
                    break;
                case IEntity.STATE_PRE:
                    break;
                case IEntity.STATE_POST_PRE:
                    break;
                case IEntity.STATE_CANCEL:
                    break;
                default:
            }
        }
    }

    public void setLineShow(boolean show) {
        this.mShowLine = show;
        notifyDataSetChanged();
    }

    public void setData(List<AppInfo> appInfos) {
        this.mAppInfoList = appInfos;
        notifyDataSetChanged();
    }

    private void ItemChanged(DownloadTask task) {
        mDownloadTask = task;
        for (int i = 0; i < mAppInfoList.size(); i++) {
            if (mAppInfoList.get(i).getApp_url().equals(task.getEntity().getUrl())) {
                notifyItemChanged(i);
            }
        }
    }

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

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

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