package com.uiuipad.appstore.activity.details;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.uiuipad.appstore.R;
import com.uiuipad.appstore.adapter.ImageAdapter;
import com.uiuipad.appstore.base.BaseActivity;
import com.uiuipad.appstore.bean.AdminAppInfo;
import com.uiuipad.appstore.bean.GlideCircleWithBorder;
import com.uiuipad.appstore.dialog.InstallDialog;
import com.uiuipad.appstore.helper.CustomSnapHelper;
import com.uiuipad.appstore.network.NetInterfaceManager;
import com.uiuipad.appstore.utils.ApkUtils;
import com.uiuipad.appstore.utils.FileUtils;
import com.uiuipad.appstore.utils.StorageUtils;
import com.uiuipad.appstore.utils.ToastUtil;
import com.uiuipad.appstore.utils.Utils;

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

import butterknife.BindView;
import butterknife.ButterKnife;

public class DetailsActivity extends BaseActivity implements DetailsContact.DetailsView {
    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 mImageAdapter;
    private InstallReceiver mInstallReceiver;
    private AdminAppInfo mAdminAppInfo;

    boolean mInstalled;
    boolean mUpdate;

    private DetailsPresenter mPresenter;


    /**
     * 设置布局
     */
    @Override
    public int getLayoutId() {
        return R.layout.activity_details;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mPresenter = new DetailsPresenter(this);
        mPresenter.attachView(this);
        mPresenter.setLifecycle(lifecycleSubject);

        Aria.download(this).register();
        rv_image.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        CustomSnapHelper snapHelper = new CustomSnapHelper();
        snapHelper.attachToRecyclerView(rv_image);
        mImageAdapter = new ImageAdapter();
        rv_image.setAdapter(mImageAdapter);

        mAdminAppInfo = (AdminAppInfo) getIntent().getSerializableExtra("appinfo");
        if (mAdminAppInfo == null) {
            ToastUtil.show("获取引用信息失败，返回重试");
            return;
        } else {
            mPresenter.getAdminAppDetails(mAdminAppInfo.getId());
        }
    }

    @Override
    public void initData() {
        mInstalled = ApkUtils.isInstalled(DetailsActivity.this, mAdminAppInfo.getApp_package());
        mUpdate = ApkUtils.isUpdate(DetailsActivity.this, mAdminAppInfo.getApp_package(), mAdminAppInfo.getApp_version_code());
        if (mInstalled) {
            if (mUpdate) {
                tv_download.setText("更新" + "(" + StorageUtils.byteToMB(mAdminAppInfo.getApp_size()) + ")");
            } else {
                tv_download.setText("打开");
            }
        } else {
            tv_download.setText("安装" + "(" + StorageUtils.byteToMB(mAdminAppInfo.getApp_size()) + ")");
        }
        tv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.canDownloadApp(DetailsActivity.this)) {
//                    ToastUtil.show("应用市场已被禁止安装");
                    InstallDialog installDialog = new InstallDialog(DetailsActivity.this);
                    installDialog.setMessage(String.format(getString(R.string.install_note), mAdminAppInfo.getApp_name()))
                            .setTitle("提示")
                            .setPositive("申请安装")
                            .setNegtive("取消")
                            .setImageUrl(mAdminAppInfo.getApp_icon())
                            .setOnClickBottomListener(new InstallDialog.OnClickBottomListener() {
                                @Override
                                public void onPositiveClick() {
                                    NetInterfaceManager.getInstance().getApplyForInstall(mAdminAppInfo.getApp_package(), mAdminAppInfo.getApp_name()
                                            , new NetInterfaceManager.onCompleteCallback() {
                                                @Override
                                                public void onComplete() {
                                                    installDialog.dismiss();
                                                }
                                            });
                                }

                                @Override
                                public void onNegtiveClick() {
                                    installDialog.dismiss();
                                }
                            });
                    installDialog.show();
                    return;
                }
                if (mInstalled && !mUpdate) {
                    ApkUtils.openApp(DetailsActivity.this, mAdminAppInfo.getApp_package());
                } else {
                    DownloadEntity entity = Aria.download(this).getFirstDownloadEntity(mAdminAppInfo.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(mAdminAppInfo)).getAsJsonObject();
                                    FileUtils.ariaDownload(DetailsActivity.this, mAdminAppInfo.getApp_url(), jsonObject);
                                }
                                break;
                            default:
                        }
                    } else {
                        JsonObject jsonObject = JsonParser.parseString(new Gson().toJson(mAdminAppInfo)).getAsJsonObject();
                        FileUtils.ariaDownload(DetailsActivity.this, mAdminAppInfo.getApp_url(), jsonObject);
                    }
                }
            }
        });

        if (mInstallReceiver == null) {
            mInstallReceiver = new InstallReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.uiuipad.appstore.PACKAGE_ADDED");
            filter.addAction("com.uiuipad.appstore.PACKAGE_REPLACED");
            filter.addAction("com.uiuipad.appstore.PACKAGE_REMOVED");
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            registerReceiver(mInstallReceiver, filter);
        }
    }

    private void setImage(AdminAppInfo info) {
        List<String> list = info.getApp_preview();
        mImageAdapter.setData(list);
    }

    @Override
    public void setAdminAppDetails(AdminAppInfo adminAppInfo) {
        if (adminAppInfo != null) {
            tv_name.setText(mAdminAppInfo.getApp_name());
            tv_company.setText(mAdminAppInfo.getApp_developer());
            detali_tv_size.setText("大小\t" + "(" + StorageUtils.byteToMB(mAdminAppInfo.getApp_size()) + ")");
            detail_tv_Developers.setText("开发者\t" + mAdminAppInfo.getApp_developer());
            tv_update_time.setText("时间\t" + mAdminAppInfo.getUpdate_time());
            tv_version.setText("版本\t" + mAdminAppInfo.getApp_version_name());
            tv_content.setText(mAdminAppInfo.getApp_remarks());
            detali_tv_version.setText("版本:" + mAdminAppInfo.getApp_version_name());
            rating_bar.setRating(mAdminAppInfo.getApp_score());
            Glide.with(this).asBitmap().load(mAdminAppInfo.getApp_icon()).transform(new GlideCircleWithBorder(this)).into(iv_icon);
            setImage(adminAppInfo);
        }
    }

    void refresh(DownloadTask task) {
        if (mAdminAppInfo.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:
            }
        }
    }

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


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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
        if (mInstallReceiver != null) {
            unregisterReceiver(mInstallReceiver);
            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);
    }

}
