package com.mjsheng.myappstore.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lzy.okserver.download.DownloadManager;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.image.ImageLoader;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.widget.Sound;

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

public class DownloadListAdapter extends RecyclerView.Adapter<DownloadListAdapter.DownloadViewHolder> {

    private Context mContext;
    private Sound sound;
    public List<AppDownloadInfo> allTask = new ArrayList<>();
    private setItemSizeListener mListener;
    private HashMap<String, DownloadViewHolder> mMaps = new HashMap<>();

    public DownloadListAdapter(Context context, setItemSizeListener listener) {
        mContext = context;
        mListener = listener;
        sound = new Sound(context);
        mMaps.clear();
    }

    public void setDatas(List<AppDownloadInfo> list) {
        allTask = list;
        mListener.setItemSize(allTask.size());
        notifyDataSetChanged();
    }

    public void addDatas(AppDownloadInfo info) {
        allTask.add(info);
        mListener.setItemSize(allTask.size());
        notifyItemInserted(allTask.size() - 1);
    }

    public void removeItem(String packageName) {
        int position = -1;
        for (int i = 0; i < allTask.size(); i++) {
            if (packageName.equals(allTask.get(i).getPackageName())) {
                position = i;
            }
        }
        if (position != -1) {
            allTask.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, allTask.size());
            mListener.setItemSize(allTask.size());
        }
    }

    public void removeItem(AppDownloadInfo info) {
        sendIntent("delete", info.getUrl(), null);
        int position = -1;
        for (int i = 0; i < allTask.size(); i++) {
            if (info.getUrl().equals(allTask.get(i).getUrl())) {
                position = i;
            }
        }
        allTask.remove(info);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, allTask.size());
        mListener.setItemSize(allTask.size());
    }


    @Override
    public DownloadViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        View v = View.inflate(parent.getContext(), R.layout.download_list_item, null);
        v.setLayoutParams(layoutParams);
        return new DownloadViewHolder(v);
    }

    @Override
    public void onBindViewHolder(DownloadViewHolder holder, int position) {
        AppDownloadInfo downloadInfo = allTask.get(position);
        holder.setData(downloadInfo);

        if (!mMaps.containsKey(downloadInfo.getUrl())) {
            mMaps.put(downloadInfo.getUrl(), holder);
        } else {
            mMaps.remove(downloadInfo.getUrl());
            mMaps.put(downloadInfo.getUrl(), holder);
        }

        holder.downloadSizeProgress.setText((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
        String downloadLength = Formatter.formatFileSize(mContext, downloadInfo.getDownloadLength());
        String totalLength = Formatter.formatFileSize(mContext, downloadInfo.getTotalLength());
        holder.downloadState.setText(downloadLength + "/" + totalLength);
        holder.downloadLl.setOnClickListener(new DownloadBtnListener(downloadInfo, holder));
        holder.cancelLl.setOnClickListener(new DownloadBtnListener(downloadInfo, holder));
        holder.progressBar.setProgress((int) downloadInfo.getDownloadLength());
        holder.progressBar.setMax((int) downloadInfo.getTotalLength());
        updateProgress(downloadInfo);
    }

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

    public interface setItemSizeListener {
        void setItemSize(int size);
    }


    private class DownloadBtnListener implements View.OnClickListener {
        private AppDownloadInfo downloadInfo;
        private DownloadViewHolder viewHolder;


        public DownloadBtnListener(AppDownloadInfo downloadInfo, DownloadViewHolder viewHolder) {
            this.downloadInfo = downloadInfo;
            this.viewHolder = viewHolder;
        }

        @Override
        public void onClick(View v) {
            sound.playSoundEffect();
            switch (v.getId()) {
                case R.id.llDownload:
                    int downloadState = downloadInfo.getState();
                    switch (downloadState) {
                        case DownloadManager.PAUSE:
                        case DownloadManager.NONE:
                        case DownloadManager.ERROR:
                            sendIntent("start", downloadInfo.getUrl(), downloadInfo);
                            break;
                        case DownloadManager.DOWNLOADING:
                        case DownloadManager.WAITING:
                            sendIntent("stop", downloadInfo.getUrl(), null);
                            break;
                        case DownloadManager.FINISH:
                            ApkUtils.install(mContext, new File(downloadInfo.getTargetPath()));
                            break;
                    }
                    break;
                case R.id.llCancle:
                    removeItem(downloadInfo);
                    break;
            }
        }
    }

    private void sendIntent(String state, String URL, AppDownloadInfo info) {
        // 发送广播通知  下载、暂停、初始化
        if (state.equals("start")) {
            AppDateInfo dateInfo = (AppDateInfo) info.getData();
            Intent msgIntent = new Intent(Utils.DOWNLOAD_START_ACTION);
            msgIntent.putExtra("URL", URL);
            msgIntent.putExtra("AppDateInfo", dateInfo);
            mContext.sendBroadcast(msgIntent);
            //            AppData.AddDownloadApp(mContext, Utils.system[Integer.parseInt(dateInfo.getXitong_id()) - 1], Utils.sonSystem[Integer.parseInt(dateInfo.getZixitong_id()) - 1], dateInfo.getApp_baoming());
            AppData.AddDownloadApp(mContext, Utils.system[Integer.parseInt("1") - 1], Utils.sonSystem[Integer.parseInt("11") - 1], info.getPackageName());

        } else if (state.equals("stop")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_STOP_ACTION);
            msgIntent.putExtra("URL", URL);
            mContext.sendBroadcast(msgIntent);
        } else if (state.equals("initialize")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_INITIALIZE_ACTION);
            msgIntent.putExtra("URL", URL);
            mContext.sendBroadcast(msgIntent);
        } else if (state.equals("delete")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_DELETE_URL_ACTION);
            msgIntent.putExtra("URL", URL);
            mContext.sendBroadcast(msgIntent);
        }
    }

    public class DownloadViewHolder extends RecyclerView.ViewHolder {

        public ImageView appIcon, downloadIv;
        public TextView title, downloadTv;
        public TextView downloadState;
        public TextView downloadSizeProgress;
        public ProgressBar progressBar;
        private LinearLayout downloadLl, cancelLl;
        public LinearLayout appBg;
        private AppDownloadInfo downloadInfo;

        public DownloadViewHolder(View parentView) {
            super(parentView);
            appBg = (LinearLayout) parentView.findViewById(R.id.app_bg);
            appIcon = (ImageView) parentView.findViewById(R.id.app_icon);
            title = (TextView) parentView.findViewById(R.id.title);
            downloadState = (TextView) parentView.findViewById(R.id.download_state);
            downloadSizeProgress = (TextView) parentView.findViewById(R.id.download_size_progress);
            progressBar = (ProgressBar) parentView.findViewById(R.id.progress_bar);
            cancelLl = (LinearLayout) parentView.findViewById(R.id.llCancle);
            downloadLl = (LinearLayout) parentView.findViewById(R.id.llDownload);
            downloadIv = (ImageView) parentView.findViewById(R.id.ivDownload);
            downloadTv = (TextView) parentView.findViewById(R.id.tvDownload);
        }

        public void setData(AppDownloadInfo downloadInfo) {
            AppDateInfo appInfo = (AppDateInfo) downloadInfo.getData();
            if (appInfo != null) {
                ImageLoader.getDefault().loadUrl(mContext, appInfo.getApp_img(), appIcon);
                title.setText(appInfo.getApp_name());
            } else {
                ImageLoader.getDefault().loadUrl(mContext, appInfo.getApp_img(), appIcon);
                title.setText(appInfo.getApp_name());
            }
        }

    }

    //更新当前进度
    public void updateProgress(AppDownloadInfo downloadInfo) {
        if (downloadInfo == null)
            return;
        DownloadViewHolder holder = mMaps.get(downloadInfo.getUrl());
        if (holder == null)
            return;
        holder.downloadInfo = downloadInfo;
        if (downloadInfo.getState() == DownloadManager.NONE || downloadInfo.getState() == DownloadManager.ERROR || downloadInfo.getState() == DownloadManager.PAUSE) {
            holder.downloadTv.setText("下载");
            holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.WAITING) {
            holder.downloadTv.setText(R.string.download_wait_text);
            holder.downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_start);
        } else if (downloadInfo.getState() == DownloadManager.FINISH) {
            if (ApkUtils.isInstalling(downloadInfo.getPackageName())) {
                holder.downloadTv.setText(mContext.getString(R.string.download_install_text));
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                holder.downloadIv.setBackgroundResource(R.drawable.download_install);
            } else {
                holder.downloadTv.setText(mContext.getString(R.string.download_install_wait));
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                holder.downloadIv.setBackgroundResource(R.drawable.download_install);
            }
        } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
            holder.downloadTv.setText("暂停");
            holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_start);
            holder.downloadSizeProgress.setText((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
            String downloadLength = Formatter.formatFileSize(mContext, downloadInfo.getDownloadLength());
            String totalLength = Formatter.formatFileSize(mContext, downloadInfo.getTotalLength());
            holder.downloadState.setText(downloadLength + "/" + totalLength);
        }
        holder.progressBar.setProgress((int) downloadInfo.getDownloadLength());
        holder.progressBar.setMax((int) downloadInfo.getTotalLength());

    }


}