package com.uiui.zyappstore.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
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.adapter.ImageAdapter;
import com.uiui.zyappstore.base.BaseActivity;
import com.uiui.zyappstore.bean.AppInfo;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.bean.GlideCircleWithBorder;
import com.uiui.zyappstore.helper.CustomSnapHelper;
import com.uiui.zyappstore.network.NetInterfaceManager;
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 java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class DetailsActivity extends BaseActivity {
    private static final String TAG = DetailsActivity.class.getSimpleName();

    @BindView(R.id.detail_tv_title)
    TextView tv_title;
    @BindView(R.id.detail_tv_name)
    TextView tv_name;
    @BindView(R.id.detail_tv_company)
    TextView tv_company;
    @BindView(R.id.detail_tv_update_time)
    TextView tv_update_time;
    @BindView(R.id.detail_tv_version)
    TextView tv_version;
    @BindView(R.id.detali_tv_content)
    TextView tv_content;
    @BindView(R.id.detali_tv_size)
    TextView detali_tv_size;
    @BindView(R.id.detail_tv_Developers)
    TextView detail_tv_Developers;
    @BindView(R.id.detali_tv_version)
    TextView detali_tv_version;
    @BindView(R.id.detail_tv_download)
    Button tv_download;
    @BindView(R.id.detail_rating_bar)
    RatingBar rating_bar;
    @BindView(R.id.detail_iv_icon)
    ImageView iv_icon;
    @BindView(R.id.detail_rv_image)
    RecyclerView rv_image;
    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;

    private ImageAdapter imageAdapter;
    private installReceiver myReceiver;
    private AppInfo appInfo;

    boolean installed;
    boolean update;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_details;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        Aria.download(this).register();
        rv_image.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        CustomSnapHelper snapHelper = new CustomSnapHelper();
        snapHelper.attachToRecyclerView(rv_image);
        imageAdapter = new ImageAdapter();
        rv_image.setAdapter(imageAdapter);

        appInfo = (AppInfo) getIntent().getSerializableExtra("appinfo");
        if (appInfo == null) {
            ToastUtil.show("获取引用信息失败，返回重试");
            return;
        } else {
            getPackageApp(appInfo.getApp_package(), appInfo.getApp_version_code());
        }
        tv_name.setText(appInfo.getApp_name());
        tv_company.setText(appInfo.getApp_developer());
        detali_tv_size.setText("大小\t" + "(" + StorageUtils.byteToMB(appInfo.getApp_size()) + ")");
        detail_tv_Developers.setText("开发者\t" + appInfo.getApp_developer());
        tv_update_time.setText("时间\t" + appInfo.getCreatetime());
        tv_version.setText("版本\t" + appInfo.getApp_version_name());
        tv_content.setText(appInfo.getApp_desc());
        detali_tv_version.setText("版本:" + appInfo.getApp_version_name());
        rating_bar.setRating((float) appInfo.getApp_score());
        Glide.with(this).asBitmap().load(appInfo.getApp_img()).transform(new GlideCircleWithBorder(this)).into(iv_icon);
        setImage(appInfo);
    }

    @Override
    protected void initData() {
        installed = ApkUtils.isInstalled(DetailsActivity.this, appInfo.getApp_package());
        update = ApkUtils.isUpdate(DetailsActivity.this, appInfo.getApp_package(), appInfo.getApp_version_code());
        if (installed) {
            if (update) {
                tv_download.setText("更新" + "(" + StorageUtils.byteToMB(appInfo.getApp_size()) + ")");
            } else {
                tv_download.setText("打开");
            }
        } else {
            tv_download.setText("安装" + "(" + StorageUtils.byteToMB(appInfo.getApp_size()) + ")");
        }
        tv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (installed && !update) {
                    ApkUtils.openApp(DetailsActivity.this, appInfo.getApp_package());
                } else {
                    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()) {
                                    tv_download.setText("安装中");
                                    ApkUtils.installApp(DetailsActivity.this, entity.getFilePath());
                                } else {
                                    Aria.download(this).load(entity.getId()).cancel(true);
                                    JsonObject jsonObject = JsonParser.parseString(new Gson().toJson(appInfo)).getAsJsonObject();
                                    FileUtils.ariaDownload(DetailsActivity.this, appInfo.getApp_url(), jsonObject);
                                }
                                break;
                            default:
                        }
                    } else {
                        JsonObject jsonObject = JsonParser.parseString(new Gson().toJson(appInfo)).getAsJsonObject();
                        FileUtils.ariaDownload(DetailsActivity.this, appInfo.getApp_url(), jsonObject);
                    }
                }
            }
        });
    }

    private void setImage(final AppInfo info) {
        List<String> list = new ArrayList<String>() {{
            this.add(info.getApp_preview1());
            this.add(info.getApp_preview2());
            this.add(info.getApp_preview3());
        }};
        imageAdapter.setData(list);
    }

    void getPackageApp(String packageName, long versionCode) {
        NetInterfaceManager.getInstance()
                .getQueryPackageAppControl()
                .getPackageApp(packageName, versionCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<AppInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("getPackageApp", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(BaseResponse<AppInfo> appInfoBaseResponse) {
                        Log.e("getPackageApp", "onNext: " + appInfoBaseResponse);
                        if (appInfoBaseResponse.code == 200) {
                            AppInfo info = appInfoBaseResponse.data;
                            if (!TextUtils.isEmpty(info.getApp_preview1())) {
                                appInfo.setApp_preview1(info.getApp_preview1());
                            }
                            if (!TextUtils.isEmpty(info.getApp_preview2())) {
                                appInfo.setApp_preview2(info.getApp_preview2());
                            }
                            if (!TextUtils.isEmpty(info.getApp_preview3())) {
                                appInfo.setApp_preview3(info.getApp_preview3());
                            }
                            appInfo.setApp_version_name(info.getApp_version_name());
                            setImage(appInfo);
                        } else {
                            scrollView.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("getPackageApp", "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("getPackageApp", "onComplete: ");
                    }
                });
    }

    void refresh(DownloadTask task) {
        if (appInfo.getApp_url().equals(task.getEntity().getUrl())) {
            switch (task.getState()) {
                case IEntity.STATE_OTHER:
                    tv_download.setText("安装");
                    break;
                case IEntity.STATE_STOP:
                    tv_download.setText("继续");
                    break;
                case IEntity.STATE_FAIL:
                    tv_download.setText("出错");
                    break;
                case IEntity.STATE_WAIT:
                    tv_download.setText("等待");
                    break;
                case IEntity.STATE_COMPLETE:
                    tv_download.setText("安装中");
                    break;
                case IEntity.STATE_RUNNING:
                    tv_download.setText(task.getPercent() + "%");
                    break;
                default:
            }
        }
    }

    @Override
    protected void setListener() {
        if (myReceiver == null) {
            myReceiver = new installReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.uiui.zyappstore.PACKAGE_ADDED");
            filter.addAction("com.uiui.zyappstore.PACKAGE_REPLACED");
            filter.addAction("com.uiui.zyappstore.PACKAGE_REMOVED");
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            registerReceiver(myReceiver, filter);
        }
    }

    public void finish(View view) {
        finish();
    }

//    public void refresh(Progress progress) {
//        switch (progress.status) {
//            case Progress.NONE:
//                tv_download.setText("安装" + "(" + appInfo.getApp_size() + "MB" + ")");
//                break;
//            case Progress.PAUSE:
//                tv_download.setText("继续");
//                break;
//            case Progress.ERROR:
//                tv_download.setText("出错");
//                break;
//            case Progress.WAITING:
//                tv_download.setText("等待");
//                break;
//            case Progress.LOADING:
//                tv_download.setText((int) (progress.fraction * 100) + "%");
//                break;
//            case Progress.FINISH:
//                tv_download.setText("安装中");
//                break;
//        }
//    }

//    class FileDownloadListener extends DownloadListener {
//
//        public FileDownloadListener(Object tag) {
//            super(tag);
//        }
//
//        @Override
//        public void onStart(Progress progress) {
//
//        }
//
//        @Override
//        public void onProgress(Progress progress) {
//            if (tag == appInfo.getApp_url()) {
//                refresh(progress);
//            }
//        }
//
//        @Override
//        public void onError(Progress progress) {
//            Throwable throwable = progress.exception;
//            if (throwable != null) throwable.printStackTrace();
//            ToastUtil.show(((AppInfo) progress.extra1).getApp_name() + "\t下载失败，请重试");
//        }
//
//        @Override
//        public void onFinish(final File file, Progress progress) {
//            tv_download.setText("安装中");
//            ToastUtil.show(((AppInfo) progress.extra1).getApp_name() + "\t下载完成");
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    ApkUtils.installApp(DetailsActivity.this, file.getAbsolutePath());
//                }
//            }).start();
//        }
//
//        @Override
//        public void onRemove(Progress progress) {
//
//        }
//    }

    public class installReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //接收安装广播
            if ("com.uiui.zyappstore.PACKAGE_ADDED".equals(action) || "com.uiui.zyappstore.PACKAGE_REPLACED".equals(action)) {
                String packageName = intent.getStringExtra("package");
                if (packageName.equalsIgnoreCase(appInfo.getApp_package())) {
                    tv_download.setText("打开");
                }
                initData();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
            Aria.download(this).unRegister();
        }
    }

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

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

    @Download.onTaskFail
    void onTaskFail(DownloadTask task, Exception e) {
        refresh(task);
    }

    @Download.onWait
    void onWait(DownloadTask task) {
        refresh(task);
    }

    @Download.onTaskStart
    void onTaskStart(DownloadTask task) {
        refresh(task);
    }

    @Download.onPre
    void onPre(DownloadTask task) {
        refresh(task);
    }

    @Download.onTaskResume
    void onTaskResume(DownloadTask task) {
        refresh(task);
    }

    @Download.onTaskStop
    void onTaskStop(DownloadTask task) {
        refresh(task);
    }

    @Download.onTaskCancel
    void onTaskCancel(DownloadTask task) {
        refresh(task);
    }


}
