package com.halo.assistant.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.common.view.VerticalItemDecoration;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.CleanApkAdapter;
import com.gh.gamecenter.feature.entity.InstallGameEntity;
import com.gh.gamecenter.fragment.MainWrapperFragment;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.lightgame.utils.Utils;

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

/**
 * Created by CsHeng on 14/12/2017.
 * <p>
 * 扫描并删除apk
 */
public class ApkCleanerFragment extends ToolbarFragment implements CleanApkAdapter.OnScanListener {

    private TextView mApkCount;
    private TextView mApkDeleteBtn;
    private CheckBox mApkSelectAll;
    private ProgressBar mScanPb;
    private TextView mNodataSkipTv;
    private TextView mNodataSkipBtn;
    private View mNodataSkipLl;
    private View mDeleteBottom;
    private View mInstallAllData;

    private CleanApkAdapter mAdapter;
    private boolean isChooseApk = false;
    private String platformRequestsId;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_apk_cleaner;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RecyclerView recyclerView = view.findViewById(R.id.apk_rv);
        mApkCount = view.findViewById(R.id.apk_count);
        mApkDeleteBtn = view.findViewById(R.id.delete_btn);
        mApkSelectAll = view.findViewById(R.id.select_game_all);
        mScanPb = view.findViewById(R.id.scan_pb);
        mNodataSkipLl = view.findViewById(R.id.reuse_none_data);
        mNodataSkipTv = mNodataSkipLl.findViewById(R.id.reuseNoneDataTv);
        mNodataSkipBtn = mNodataSkipLl.findViewById(R.id.reuseResetLoadTv);

        mDeleteBottom = view.findViewById(R.id.delete_bottom);
        mInstallAllData = view.findViewById(R.id.select_game_installed_ll);

        mApkDeleteBtn.setOnClickListener(this);
        mNodataSkipBtn.setOnClickListener(this);

        isChooseApk = requireArguments().getBoolean(EntranceConsts.KEY_IS_CHOOSE_APK, false);
        platformRequestsId = requireArguments().getString(EntranceConsts.KEY_PLATFORM_REQUESTS_ID, "");
        setNavigationTitle(isChooseApk ? getString(R.string.title_choose_apk) : getString(R.string.title_clean_apk));
        mNodataSkipLl.setVisibility(View.GONE);

        mAdapter = new CleanApkAdapter(getContext(), this, mApkDeleteBtn, mApkSelectAll, isChooseApk);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new VerticalItemDecoration(getContext(), 8, true));
        recyclerView.setAdapter(mAdapter);

        mApkSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            ArrayMap<Integer, Boolean> selectPosition = new ArrayMap<>();
            ArrayMap<Integer, Boolean> selectPosition1 = mAdapter.getSelectPosition();
            int itemCount = mAdapter.getItemCount();
            if (isChecked) {
                MtaHelper.onEvent("我的光环_设置", "安装包清理", "选中");
                for (int i = 0; i < itemCount; i++) {
                    selectPosition.put(i, true);
                }
            } else {
                MtaHelper.onEvent("我的光环_设置", "安装包清理", "取消选中");
                int selectCount = 0;
                for (Integer integer : selectPosition1.keySet()) {
                    if (selectPosition1.get(integer)) {
                        selectCount++;
                    }
                }

                if (selectCount != itemCount) {
                    return;
                }

                for (int i = 0; i < itemCount; i++) {
                    selectPosition.put(i, false);
                }
            }

            mAdapter.setSelectPosition(selectPosition);
            mAdapter.notifyItemRangeChanged(0, itemCount);
            mAdapter.checkBoxControl(isChecked, 0);
        });

        if (isChooseApk) {
            mApkSelectAll.setVisibility(View.GONE);
            mNodataSkipBtn.setVisibility(View.GONE);
            mNodataSkipTv.setText("暂无安装包");
        } else {
            mNodataSkipBtn.setText("去首页看看");
            mNodataSkipTv.setText("安装包已清理干净\n快去发现更多好玩的游戏吧！");
            mNodataSkipTv.setLineSpacing(0, 1.5f);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.delete_btn) {
            String s = mApkDeleteBtn.getText().toString();
            if ("停止扫描".equals(s)) {
                MtaHelper.onEvent("我的光环_设置", "安装包清理", "停止扫描");
                mAdapter.isStopScan();
            } else {
                final List<InstallGameEntity> apkList = mAdapter.getApkList();
                final ArrayMap<Integer, Boolean> selectPosition = mAdapter.getSelectPosition();
                if (isChooseApk) {
                    InstallGameEntity installGameEntity = null;
                    for (Integer integer : selectPosition.keySet()) {
                        if (selectPosition.get(integer)) {
                            installGameEntity = apkList.get(integer);
                            break;
                        }
                    }
                    if (installGameEntity == null) {
                        ToastUtils.showToast("请选择需要上传的安装包");
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra(EntranceConsts.KEY_PACKAGENAME, installGameEntity.getPackageName());
                        intent.putExtra(EntranceConsts.KEY_PATH, installGameEntity.getGamePath());
                        intent.putExtra(EntranceConsts.KEY_FORMAT, installGameEntity.getFormat());
                        intent.putExtra(EntranceConsts.KEY_VERSION_CODE, installGameEntity.getVersionCode());
                        intent.putExtra(EntranceConsts.KEY_PLATFORM_REQUESTS_ID, platformRequestsId);
                        requireActivity().setResult(Activity.RESULT_OK, intent);
                        requireActivity().finish();
                    }
                    return;
                }
                if ("一键删除".equals(s)) {
                    ToastUtils.showToast("请选择需要删除的安装包");
                    return;
                }
                MtaHelper.onEvent("我的光环_设置", "安装包清理", "一键删除");

                for (int i = 0; i < apkList.size(); i++) {
                    if (selectPosition.get(i) && apkList.get(i).getInstallStatus() == 1) {
                        DialogHelper.showCenterWarningDialog(requireContext(), "删除安装包"
                                , Html.fromHtml(getString(R.string.delete_apk_hint))
                                , "取消 ", "确定"
                                , () -> {
                                    deleteApk(apkList, selectPosition);
                                    return null;
                                }, null);
                        return;
                    }
                }

                deleteApk(apkList, selectPosition);
            }
        } else if (id == R.id.reuseResetLoadTv) {
            MainActivity.skipToMainActivity(getActivity(), MainWrapperFragment.INDEX_HOME);
        }
    }

    private void deleteApk(List<InstallGameEntity> apkList, ArrayMap<Integer, Boolean> selectPosition) {
        long size = 0;
        for (int i = 0; i < apkList.size(); i++) {
            if (selectPosition.get(i)) {
                InstallGameEntity installGameEntity = apkList.get(i);
                size = size + installGameEntity.getGameSize();
                File file = new File(installGameEntity.getGamePath());
                if (file.isFile() && file.exists()) {
                    file.delete();
                    mAdapter.deleteApk(i);
                    i--;
                }
            }
        }

        double allSize = (((float) size / 1024) / 1024);
        DecimalFormat df = new DecimalFormat("#.00");
        String sizeName = df.format(allSize) + "MB";
        Utils.toast(getContext(), "删除成功，已为您节省" + sizeName + "空间");
        mApkDeleteBtn.setText("一键删除");
        mAdapter.notifyDataSetChanged(); // 刷新Adapter position

        updateScanData();

        if (apkList.size() == 0) { // 全部删除
            mNodataSkipLl.setVisibility(View.VISIBLE);
            mInstallAllData.setVisibility(View.GONE);
            mDeleteBottom.setVisibility(View.GONE);
        }

        DownloadManager.getInstance().clearTasksThatFileBeenDeleted();
    }

    private void updateScanData() {
        long allSize = 0;
        List<InstallGameEntity> apkList = mAdapter.getApkList();
        for (InstallGameEntity installGameEntity : apkList) {
            allSize = allSize + installGameEntity.getGameSize();
        }

        double size = (((float) allSize / 1024) / 1024);
        DecimalFormat df = new DecimalFormat("0.00");
        String sizeName = df.format(size) + "MB";

        mApkCount.setText(Html.fromHtml(getString(R.string.clean_apk_count, apkList.size(), sizeName)));
    }

    @Override
    public void onScanOver() {
        if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
            mApkDeleteBtn.setTextColor(Color.WHITE);
            mApkDeleteBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);

            mScanPb.setVisibility(View.GONE);
            if (!isChooseApk) {
                updateScanData();
                mApkDeleteBtn.setText("立即删除");
                mApkSelectAll.setVisibility(View.VISIBLE);
                mApkSelectAll.setChecked(true);
            } else {
                mApkCount.setText("扫描完成");
                mApkDeleteBtn.setText("确定");
            }
        }
    }

    @Override
    public void noData() {
        if (isChooseApk) {
            mNodataSkipBtn.setVisibility(View.GONE);
        }
        mNodataSkipBtn.setText("去首页看看");
        mNodataSkipTv.setText("暂无安装包");
        mNodataSkipLl.setVisibility(View.VISIBLE);
        mInstallAllData.setVisibility(View.GONE);
        mDeleteBottom.setVisibility(View.GONE);
    }
}
