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.content.res.Configuration;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.base.MyApplication;
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.image.ImageLoader;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.utils.update.ToastTool;
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;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by chris on 2016/1/26.
 */
public class RecommendAdapter extends BaseAdapter {
    public RecommendItemClick itemClick;
    private List<AppDateInfo> list = new ArrayList<>();
    private Context mContext;
    private Sound sound;
    private HashMap<String, ViewHolder> mMaps = new HashMap<>();
    private DownloadReceiver downloadReceiver;
    private String userVip;

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

    public void Registeredbroadcasting() {
        if (downloadReceiver == null) {
            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;
        mContext.unregisterReceiver(downloadReceiver);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int orientation = mContext.getResources().getConfiguration().orientation;
        final AppDateInfo info = list.get(position);
        final ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.item_recommened, null);
            convertView.setLayoutParams(new AbsListView.LayoutParams(-1, -1));
            holder = new ViewHolder(convertView);
            convertView.setTag(R.string.view_holder, holder);
        } else {
            holder = (ViewHolder) convertView.getTag(R.string.view_holder);
        }
        holder.ivAppIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClick != null) {
                    itemClick.itemClick(info);
                }
            }
        });
        ImageLoader.getDefault().loadUrlRound(mContext, info.getApp_img(), holder.ivAppIcon);
        if (position == list.size() - 1 || (position + 1) % 4 == 0) {
            //            holder.lineView.setVisibility(View.INVISIBLE);
        } else {
            //            holder.lineView.setVisibility(View.VISIBLE);
        }
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            //            holder.lineView.setVisibility(View.INVISIBLE);
        }
        //by mjsheng 商场修改
        //        long start = (long) Double.parseDouble(info.getApp_pfen());

        try {
            float f = Float.valueOf(info.getApp_pfen().trim()).floatValue();
            holder.ratingbar.setStar(f);
        } catch (NumberFormatException nfe) {
            Log.e("NumberFormatException: ", nfe.getMessage());
        }
        holder.tvAppName.setText(info.getApp_name());
        if (!TextUtils.isEmpty(info.getApp_title())) {
            holder.appDesc.setMaxWidth((int) mContext.getResources().getDimension(R.dimen.PX300x));
            holder.appDesc.setText(Utils.ToDBC(info.getApp_title()));
        }

        long s = (long) Double.parseDouble(info.getApp_size());
        String totalLength = Utils.fmtSpace(s);
        //        Log.e("mjsheng", "long是多少：：：：：" + s + "----------totalLength---" + totalLength);
        if (!totalLength.isEmpty()) {
            holder.app_size.setText(totalLength);
        }

        if (!mMaps.containsKey(info.getApp_file())) {
            mMaps.put(info.getApp_file(), holder);
        }
        // 初始化item下载状态
        sendIntent("initialize", info.getApp_file(), null);
        holder.downloadLl.setTag(info.getApp_file());
        if (holder.downloadInfo != null) {
            updateProgress(holder.downloadInfo);
        } else {
            isUpdate(info.getApp_baoming(), info.getApp_banben(), holder.downloadLl, holder.downloadIv, holder.downloadTv);
        }
        //主页下载按钮点击逻辑
        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.ERROR:
                                sendIntent("start", info.getApp_file(), info);
                                break;
                            case DownloadManager.NONE:
                                if (SaveListUtils.isDownLoading(info.getApp_baoming())) {
                                    ToastTool.show("正在下载中,请稍后");
                                    return;
                                } else {
                                    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()));
                                //                                ApkUtils.installRx(mContext,holder.downloadInfo.getPackageName(),holder.downloadInfo.getTargetPath());
                                //ApkUtils.installApkInSilence(holder.downloadInfo.getTargetPath(), holder.downloadInfo.getPackageName());
                                //修改逻辑，安装中的应用不应该再次安装
                                ToastTool.show(holder.downloadInfo.getPackageName() + "正在安装中");
                                break;
                        }
                    } else {
                        //by mjsheng
                        //                        sendIntent("start", info.getApp_file(), info);
                        if (SaveListUtils.isDownLoading(info.getApp_baoming())) {
                            ToastTool.show("正在下载中");
                            return;
                        }
//                        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", "RecommendAdapter未激活");
                }
            }
        });
        return convertView;
    }

    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) {
            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) {
            }
        } 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));
                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(info.getXitong_id()) - 1], Utils.sonSystem[Integer.parseInt(info.getZixitong_id()) - 1], info.getApp_baoming());
            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 interface RecommendItemClick {
        void itemClick(AppDateInfo info);
    }

    private class ViewHolder {
        private ImageView ivAppIcon, downloadIv;
        private TextView tvAppName, downloadTv;
        private LinearLayout downloadLl;
        private AppDownloadInfo downloadInfo;
        private StarRatingBar ratingbar;
        private TextView appDesc;
        public LinearLayout mLayout;
        private View lineView;
        private TextView app_size;


        private ViewHolder(View convertView) {
            mLayout = convertView.findViewById(R.id.category_bg);
            ivAppIcon = convertView.findViewById(R.id.ivAppIcon);
            tvAppName = convertView.findViewById(R.id.tvAppName);
            appDesc = convertView.findViewById(R.id.tvDesc);
            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);
            lineView = convertView.findViewById(R.id.line);
            app_size = convertView.findViewById(R.id.app_size);
        }

    }

    //更新当前进度
    private void updateProgress(AppDownloadInfo downloadInfo) {
        if (downloadInfo == null)
            return;
        RecommendAdapter.ViewHolder 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 DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, final Intent intent) {
            if (Utils.DOWNLOAD_SERVICE_ACTION.equals(intent.getAction())) {
                Observable.create(new Observable.OnSubscribe<AppDownloadInfo>() {
                    @Override
                    public void call(Subscriber<? super AppDownloadInfo> subscriber) {
                        AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("DownloadInfo");
                        subscriber.onNext(downloadInfo);
                        subscriber.onCompleted();
                    }

                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<AppDownloadInfo>() {
                            @Override
                            public void onNext(AppDownloadInfo appDownloadInfo) {
                                Log.e("mjsheng", "RecommendAdapter----state::" + appDownloadInfo.getState() + "--------Progress::" + appDownloadInfo.getProgress());
                                updateProgress(appDownloadInfo); //更新进度
                            }

                            @Override
                            public void onCompleted() {
                                Log.e("mjsheng", "onCompleted");
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("mjsheng", "onError");
                            }
                        });
            } 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())) {
                RecommendAdapter.this.notifyDataSetChanged();
            }
        }

    }

    private void deleteTaskForPackageName(String packageName) {
        //  下载管理服务 删除对应任务
        Intent msgIntent = new Intent(Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION);
        msgIntent.putExtra("packageName", packageName);
        mContext.sendBroadcast(msgIntent);
    }
}