package com.mjsheng.myappstore.adapter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okserver.download.DownloadManager;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.bean.AppContentInfo;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.download.StorageUtils;
import com.mjsheng.myappstore.image.ImageLoader;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.MySQLData;
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 AppUpdateListAdapter extends RecyclerView.Adapter<AppUpdateListAdapter.AppUpdateViewHolder>  {

    private Context mContext;
    private List<AppContentInfo> mDataList = new ArrayList<>();
    private Sound sound;
    private HashMap<String, AppUpdateViewHolder> mMaps = new HashMap<>();
    private String userVip;
    private setItemSizeListener mListener;

    public AppUpdateListAdapter(Context context, setItemSizeListener listener) {
        mContext = context;
        mListener = listener;
        mDataList = new ArrayList<>();
        sound = new Sound(context);
        userVip = MySQLData.GetData(context,  CommonDatas.SP_USER_VIP);
        mMaps.clear();
    }


    public void loadmore(List<AppContentInfo> mList) {
        int number = mDataList.size();
        mDataList.addAll(mList);
        notifyItemRangeInserted(number,mDataList.size());
    }

    @Override
    public AppUpdateViewHolder 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.update_app_list_item, null);
        v.setLayoutParams(layoutParams);
        return new AppUpdateViewHolder(v);
    }

    @Override
    public void onBindViewHolder(AppUpdateViewHolder holder, int position) {
        AppContentInfo info = mDataList.get(position);
        if (!mMaps.containsKey(info.getApp_file())) {
            mMaps.put(info.getApp_file(), holder);
        }else {
            mMaps.remove(info.getApp_file());
            mMaps.put(info.getApp_file(), holder);
        }
        // 初始化item下载状态
        sendIntent("initialize",info.getApp_file(),null);
        if (info != null) {
            ImageLoader.getDefault().loadUrl(mContext, info.getApp_img(),  holder.appIcon);
            holder.title.setText(info.getApp_name());
            String version = info.getApp_banben().replaceAll("[a-zA-Z]", "").trim();
            if (!TextUtils.isEmpty(version)) {
                if (!version.contains("v") || !version.contains("V")) {
                    holder.appVersion.setText("v" + version);
                } else {
                    holder.appVersion.setText(version);
                }
            } else {
                holder.appVersion.setText("");
            }
            holder.appSize.setText(StorageUtils.size((long) Double.parseDouble(info.getApp_size())));

            holder.downloadLl.setOnClickListener(new OnButtonClickListener(info , holder));

        }
    }

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

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

    public void setDatas(List<AppContentInfo> dataList) {
        mDataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public void addDatas(AppContentInfo info) {
        int position = -1;
        for (int i = 0; i < mDataList.size(); i++){
            if (info.getApp_file().equals(mDataList.get(i).getApp_file())){
                position = i;
            }
        }
        if (position != -1) {
            mDataList.set(position,info);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, mDataList.size());
            mListener.setItemSize(mDataList.size());
        }else {
            mDataList.add(info);
            mListener.setItemSize(mDataList.size());
            notifyItemInserted(mDataList.size() - 1);
        }
    }

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

    public void  removeUpItem(String packageName) {
        int position = -1;
        for (int i = 0; i < mDataList.size(); i++){
            if (packageName.equals(mDataList.get(i).getApp_baoming())){
                position = i;
            }
        }
        if (position != -1) {
            mDataList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, mDataList.size());
            mListener.setItemSize(mDataList.size());
        }
    }
    private void sendIntent(String state, String URL, AppContentInfo info){
        // 发送广播通知  下载、暂停、初始化
        if (state.equals("start")) {
            AppDateInfo dateInfo = new AppDateInfo();
            dateInfo.setApp_file(info.getApp_file());
            dateInfo.setApp_baoming(info.getApp_baoming());
            dateInfo.setApp_size(info.getApp_size());
            dateInfo.setApp_name(info.getApp_name());
            dateInfo.setApp_img(info.getApp_img());
            dateInfo.setApp_banben(info.getApp_banben());
            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("1") - 1], Utils.sonSystem[Integer.parseInt("11") - 1], info.getApp_baoming());

        }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);
        }
    }
    public  class AppUpdateViewHolder extends RecyclerView.ViewHolder{
        public ImageView appIcon,downloadIv;
        public TextView title, downloadTv;
        private TextView appVersion;
        private TextView appSize;
        private LinearLayout downloadLl;
        private AppDownloadInfo downloadInfo;
        public RelativeLayout appBg;


        public AppUpdateViewHolder(View itemView) {
            super(itemView);
            appBg = (RelativeLayout) itemView.findViewById(R.id.app_bg);
            appIcon = (ImageView) itemView
                    .findViewById(R.id.app_icon);
            title = (TextView) itemView.findViewById(R.id.title);
          appVersion = (TextView) itemView
                    .findViewById(R.id.app_version);
            appSize = (TextView) itemView
                    .findViewById(R.id.app_size);
            downloadLl = (LinearLayout) itemView.findViewById(R.id.llDownload);
            downloadIv = (ImageView) itemView.findViewById(R.id.ivDownload);
            downloadTv = (TextView) itemView.findViewById(R.id.tvDownload);
        }
    }
    //按钮按下的类
    private class OnButtonClickListener implements View.OnClickListener {
        private AppUpdateViewHolder viewHolder;
        private AppContentInfo info;

        public OnButtonClickListener(AppContentInfo info , AppUpdateViewHolder viewHolder) {
            this.info = info;
            this.viewHolder = viewHolder;
        }

        @Override
        public void onClick(View v) {
            sound.playSoundEffect();
            switch (v.getId()) {
                case R.id.llDownload:
                    if (userVip.equals("1")) {
                    if (viewHolder.downloadInfo != null) {
                        switch (viewHolder.downloadInfo.getState()) {
                            case DownloadManager.PAUSE:
                            case DownloadManager.NONE:
                            case DownloadManager.ERROR:
                                sendIntent("start",info.getApp_file(),info);
                                break;
                            case DownloadManager.DOWNLOADING:
                            case DownloadManager.WAITING:
                                sendIntent("stop",info.getApp_file(),null);
                                break;
                            case DownloadManager.FINISH:
                                ApkUtils.install(mContext, new File(viewHolder.downloadInfo.getTargetPath()));
                                break;
                        }
                    } else {
                        sendIntent("start",info.getApp_file(),info);
                    }
                    } else {
                        Log.e("mjsheng", "AppUpdateLisAdapter未激活");
                    }
                    break;
            }
        }
    }


    //更新apk下载进度
    public void updateProgress(AppDownloadInfo downloadInfo) {
        if (downloadInfo == null) return;
        AppUpdateViewHolder holder = mMaps.get(downloadInfo.getUrl());
        if (mDataList.size() > 0) {
            if (downloadInfo.getUrl().equals(mDataList.get(0).getApp_file())) {
                notifyItemChanged(0);
            }
        }
        if (holder == null) {
            return;
        } else {
            holder.downloadInfo = downloadInfo;
            if (downloadInfo.getState() == DownloadManager.NONE || downloadInfo.getState() == DownloadManager.PAUSE || downloadInfo.getState() == DownloadManager.ERROR) {
                holder.downloadTv.setText("已暂停");
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                holder.downloadIv.setBackgroundResource(R.drawable.download_continue);
                return;
            }  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_continue);
                return;
            } else if (downloadInfo.getState() == DownloadManager.FINISH) {
                holder.downloadTv.setText(R.string.download_install_text);
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                holder.downloadIv.setBackgroundResource(R.drawable.download_install);
            } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                holder.downloadTv.setText((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                holder.downloadIv.setBackgroundResource(R.drawable.download_start);
            }else if (downloadInfo.getState() == 10){
                holder.downloadInfo = null;
                isUpdate(downloadInfo.getPackageName(),downloadInfo.getVersion(),downloadInfo.getUrl(),holder.downloadLl,holder.downloadIv, holder.downloadTv);

            }
        }
    }
    private void isUpdate(String packageName , String banben, String URL, LinearLayout downloadLl, ImageView downloadIv, TextView downloadTv){
        PackageInfo packageInfo = null;
        try {
            packageInfo = mContext.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        if (packageInfo != null) {
            try {
                if (Utils.isUpdate(packageInfo.versionName,banben) == true) {
                    downloadLl.setTag(R.string.download_btn_update, packageInfo.applicationInfo.name);
                    downloadTv.setText(mContext.getString(R.string.download_btn_update));
                    downloadIv.setBackgroundResource(R.drawable.download_update);
                    downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                } else {
                   removeItem(URL);
                }
            } catch (Exception e) {
            }
        }else {
            downloadTv.setText(mContext.getString(R.string.download_start_text));
            downloadIv.setBackgroundResource(R.drawable.download_start);
            downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
        }
    }

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


    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Utils.DOWNLOAD_SERVICE_ACTION.equals(intent.getAction())) {
                AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("DownloadInfo");
                updateProgress(downloadInfo); //更新进度
            }
        }

    }
}