package com.mjsheng.myappstore.adapter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.widget.RecyclerView;
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.DownloadInfo;
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.callback.MyItemClickListener;
import com.mjsheng.myappstore.comm.CommonDatas;
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.view.StarRatingBar;
import com.mjsheng.myappstore.widget.Sound;

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

public class SubjectMoreAdapter extends RecyclerView.Adapter<SubjectMoreAdapter.SubjectMoreViewHolder> {

    private List<AppDateInfo> mDatas = new ArrayList<>();
    private Context mContext;
    private Sound sound;
    private HashMap<String, SubjectMoreViewHolder> mMaps = new HashMap<>();
    private DownloadReceiver downloadReceiver;
    private String userVip;
    private MyItemClickListener mListener;

    public SubjectMoreAdapter(Context context, List<AppDateInfo> datas, MyItemClickListener mListener) {
        mContext = context;
        this.mDatas.addAll(datas);
        this.mListener = mListener;
        sound = new Sound(context);
        mMaps.clear();
        userVip = MySQLData.GetData(context, CommonDatas.SP_USER_VIP);
        Registeredbroadcasting();
    }

    public void Registeredbroadcasting() {
        /* 注册广播 */
        downloadReceiver = new DownloadReceiver();
        IntentFilter mScreenOnFilter = new IntentFilter(Utils.DOWNLOAD_SERVICE_ACTION);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_REPLACED);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_REMOVED);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_ADDED);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_ALLTASK_ACTION);
        mContext.registerReceiver(downloadReceiver, mScreenOnFilter);
    }

    public void UnregisterReceiver() {
        // 注销广播接收
        if (downloadReceiver == null) return;
        if (downloadReceiver.isOrderedBroadcast())
            mContext.unregisterReceiver(downloadReceiver);
    }

    public AppDateInfo getData(int position) {
        if (mDatas.size() - 1 >= position) {
            return mDatas.get(position);
        } else {
            return null;
        }
    }

    public void loadmore(List<AppDateInfo> mList) {
        mDatas.addAll(mList);
        notifyItemInserted(mDatas.size() - 1);
    }

    public void setmDatas(List<AppDateInfo> mList) {
        mDatas = mList;
        notifyDataSetChanged();
    }


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

    @Override
    public void onBindViewHolder(final SubjectMoreViewHolder holder, final int position) {
        final AppDateInfo info = mDatas.get(position);
        ImageLoader.getDefault().loadUrlRound(mContext, info.getApp_img(), holder.appIcon);

        holder.appName.setText(info.getApp_name());
        try {
            long s = (long) Double.parseDouble(info.getApp_size());
            String totalLength = Utils.fmtSpace(s);
            //        Log.e("mjsheng", "long是多少：：：：：" + s + "----------totalLength---" + totalLength);
            if (!totalLength.isEmpty()) {
                holder.appSize.setText(totalLength);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("fht", e.getMessage());

        }

//        holder.appSize.setText(StorageUtils.size((long) Double.parseDouble(info.getApp_size())));

        holder.updateTime.setText(mContext.getResources().getString(R.string.app_update_time_text_format, info.getApp_down()));
        //by mjsheng 商城
        try {
            float f = Float.valueOf(info.getApp_pfen().trim()).floatValue();
            holder.ratingbar.setStar(f);
        } catch (NumberFormatException nfe) {
            Log.e("NumberFormatException: ", nfe.getMessage());
        }
//        holder.appDesc.setText(Utils.ToDBC(info.getApp_title()));


        if (!mMaps.containsKey(info.getApp_file())) {
            mMaps.put(info.getApp_file(), holder);
        }
        // 初始化item下载状态
        sendIntent("initialize", info.getApp_file(), null);
        holder.appIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onItemClick(v, position);
            }
        });
        holder.downloadLl.setTag(info.getApp_file());
        if (holder.downloadInfo != null) {
            updateProgress(holder.downloadInfo);
            Log.e("fht", "updateProgress");
        } else {
            isUpdate(info.getApp_baoming(), info.getApp_banben(), holder.downloadLl, holder.downloadIv, holder.downloadTv);
            Log.e("fht", "isUpdate");
        }
        holder.downloadLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sound.playSoundEffect();
                if (userVip.equals("1")) {
                    Registeredbroadcasting();
                    String s = (String) v.getTag(R.string.download_btn_had);
                    if (v.getTag(R.string.download_btn_had) != null && s.equals(info.getApp_baoming())) {
                        ApkUtils.openApp(mContext, v);
                        return;
                    }
                    if (holder.downloadInfo != null) {
                        switch (holder.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(holder.downloadInfo.getTargetPath()));
                                break;
                        }
                    } else {
//                        OkGo.post(Configure.HTTP_TAG_DOWNLOAD_URL)
//                                .params("key", Configure.HTTP_KEY)
//                                .params("sn", Utils.getSerial())
//                                .params("package", info.getApp_baoming())
//                                .tag(this)
//                                .cacheKey(Configure.HTTP_TAG_DOWNLOAD_URL + java.net.URLEncoder.encode(info.getApp_baoming()))
//                                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
//                                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
//                                    @Override
//                                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        sendIntent("start", info.getApp_file(), info);
//                                    }
//                                });
                    }
                } else {
                    Log.e("mjsheng", "SubjectMoreAdapter未激活");
                }
            }
        });
    }

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

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

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    private void isUpdate(String packageName, String banben, LinearLayout downloadLl, ImageView downloadIv, TextView downloadTv) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = mContext.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("fht", "NameNotFoundException：" + e.getMessage());
            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 {
                    downloadLl.setTag(R.string.download_btn_had, packageInfo.packageName);
                    downloadTv.setText(mContext.getString(R.string.open_text));
                    downloadIv.setBackgroundResource(R.drawable.download_open);
                    downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                }
            } catch (Exception e) {
                Log.e("fht", e.getMessage());
            }
        } else {
            downloadLl.setTag(R.string.download_btn_had, null);
            DownloadInfo downloadInfo = ApkUtils.getDownloadInfoByPackageName(packageName);
            if (downloadInfo != null) {
                downloadTv.setText(R.string.download_wait_text);
                 downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
                 downloadIv.setBackgroundResource(R.drawable.download_continue);
            } else {
                downloadTv.setText(mContext.getString(R.string.download_start_text));
//            downloadTv.setText("???");
                downloadIv.setBackgroundResource(R.drawable.download_start);
                downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            }
        }
    }

    private void sendIntent(String state, String URL, AppDateInfo info) {
        // 发送广播通知  下载、暂停、初始化
        if (state.equals("start")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_START_ACTION);
            msgIntent.putExtra("URL", URL);
            msgIntent.putExtra("AppDateInfo", info);
            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);
        }
    }


    //更新当前进度
    private void updateProgress(AppDownloadInfo downloadInfo) {
        if (downloadInfo == null)
            return;
        SubjectMoreViewHolder holder = mMaps.get(downloadInfo.getUrl());
        if (holder == null)
            return;
        holder.downloadInfo = downloadInfo;
        if (downloadInfo.getState() == DownloadManager.NONE) {
            holder.downloadTv.setText(R.string.download_continue_text);
            holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.ERROR) {
            holder.downloadTv.setText(mContext.getString(R.string.download_start_text));
            holder.downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_start);
        } else if (downloadInfo.getState() == DownloadManager.PAUSE) {
            holder.downloadTv.setText(mContext.getString(R.string.download_continue_text));
            holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.WAITING) {
            holder.downloadTv.setText(mContext.getString(R.string.download_wait_text));
            holder.downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.FINISH) {
            //            deleteTaskForPackageName(downloadInfo.getPackageName());
            if (ApkUtils.isAvailable(mContext, new File(downloadInfo.getTargetPath()))) {
                holder.downloadTv.setText(mContext.getString(R.string.open_text));
                holder.downloadIv.setBackgroundResource(R.drawable.download_open);
                holder.downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            } else {
                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((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
            holder.downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            holder.downloadIv.setBackgroundResource(R.drawable.download_start);
        } else if (downloadInfo.getState() == 10) {
            holder.downloadInfo = null;
            isUpdate(downloadInfo.getPackageName(), downloadInfo.getVersion(), holder.downloadLl, holder.downloadIv, holder.downloadTv);
        }
    }


    public class SubjectMoreViewHolder extends RecyclerView.ViewHolder {
        public ImageView appIcon, downloadIv;
        public TextView appName, downloadTv;
        public TextView appSize;
        public TextView appDesc;
        public TextView updateTime;
        public StarRatingBar ratingbar;
        private LinearLayout downloadLl;
        private AppDownloadInfo downloadInfo;
        public RelativeLayout appBg;

        private SubjectMoreViewHolder(View convertView) {
            super(convertView);
            appBg = convertView.findViewById(R.id.app_bg);
            appIcon = convertView.findViewById(R.id.app_icon);
            appName = convertView.findViewById(R.id.app_name);
            appSize = convertView.findViewById(R.id.app_size);
            ratingbar = convertView.findViewById(R.id.ratingbar);
            ratingbar.setmClickable(false);
            downloadLl = convertView.findViewById(R.id.llDownload);
            downloadIv = convertView.findViewById(R.id.ivDownload);
            downloadTv = convertView.findViewById(R.id.tvDownload);
            updateTime = convertView.findViewById(R.id.app_update_time);
            appDesc = convertView.findViewById(R.id.app_desc);
        }
    }


    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");
                Log.e("mjsheng", "SubjectMoreAdapter----state::" + downloadInfo.getState() + "--------Progress::" + downloadInfo.getProgress());
                updateProgress(downloadInfo); //更新进度
            } else if (Utils.ACTION_PACKAGE_ADDED.equals(intent.getAction()) ||
                    Utils.ACTION_PACKAGE_REPLACED.equals(intent.getAction()) ||
                    Utils.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) ||
                    Utils.DOWNLOAD_ALLTASK_ACTION.equals(intent.getAction())
            ) {
                SubjectMoreAdapter.this.notifyDataSetChanged();
            }

        }

    }
}
