package com.gh.gamecenter.download;

import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.common.xapk.XapkDialogHelper;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.xapk.XapkInstaller;
import com.gh.common.xapk.XapkUnzipStatus;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.databinding.DownloadmanagerBinding;
import com.gh.gamecenter.eventbus.EBDownloadChanged;
import com.gh.gamecenter.common.eventbus.EBMiPush;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.fragment.MainWrapperFragment;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DataWatcher;
import com.lightgame.download.DownloadConfig;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * 下载管理 fragment
 *
 * @author 黄壮华
 */
public class GameDownloadFragment extends BaseFragment implements View.OnClickListener {

    private DownloadmanagerBinding mBinding;

    GameDownloadFragmentAdapter adapter;
    RelativeLayout.LayoutParams rparams;

    private String url;

    private boolean isScroll;

    private DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            @Nullable Integer location = adapter.getLocation(downloadEntity.getUrl());
            String xapkStatus = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);
            if (location != null && XapkUnzipStatus.UNZIPPING.name().equals(xapkStatus)) {

                if (location >= adapter.getDoneList().size()) return;

                adapter.getDoneList().set(location, downloadEntity);
                adapter.notifyItemChanged(location + 1);
                return;
            }

            if (downloadEntity.getStatus().equals(DownloadStatus.done) && ExtensionsKt.isSimulatorGame(downloadEntity)) {
                adapter.initMap();
                adapter.notifyDataSetChanged();
                int listSize = adapter.getDownloadingList().size() + adapter.getDoneList().size();
                mBinding.reuseNoneData.getRoot().setVisibility(listSize > 0 ? View.GONE : View.VISIBLE);
                EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, listSize));
            }

            if (downloadEntity.getStatus().equals(DownloadStatus.downloading)
                    || downloadEntity.getStatus().equals(DownloadStatus.pause)
                    || downloadEntity.getStatus().equals(DownloadStatus.waiting)) {
                adapter.notifyItemChanged(adapter.getBase());
            }

            if (location != null) {
                if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
                    // 检查对应下载列表中是否存在该数据
                    boolean isContains = false;
                    for (DownloadEntity entity : adapter.getDownloadingList()) {
                        if (entity.getUrl().equals(downloadEntity.getUrl())) {
                            isContains = true;
                            break;
                        }
                    }
                    if (isContains) {
                        // 删除下载中列表对应数据
                        if (adapter.getDownloadingList().size() == 1) {
                            location = adapter.getLocation(downloadEntity.getUrl());
                            if (location != null) {
                                adapter.getDownloadingList().remove(location.intValue());
                                adapter.initLocationMap();
                                adapter.notifyItemRangeRemoved(adapter.getBase(), 2);
                            }
                        } else {
                            location = adapter.getLocation(downloadEntity.getUrl());
                            if (location != null) {
                                adapter.getDownloadingList().remove(location.intValue());
                                adapter.initLocationMap();
                                adapter.notifyItemRemoved(adapter.getBase() + location + 1);
                                adapter.notifyItemChanged(adapter.getBase() + 1);
                            }
                        }

                        // 添加进已完成列表
                        if (adapter.getDoneList().isEmpty()) {
                            adapter.getDoneList().add(0, downloadEntity);
                            adapter.initLocationMap();
                            adapter.notifyItemRangeInserted(0, 2);
                        } else {
                            adapter.getDoneList().add(0, downloadEntity);
                            adapter.initLocationMap();
                            adapter.notifyItemInserted(1);
                        }

                    } else {
                        location = adapter.getLocation(downloadEntity.getUrl());
                        if (location != null) {
                            adapter.notifyItemChanged(location + 1);
                        }
                    }

                    adapter.getUrlMap().put(PackageUtils.getPackageNameByPath(HaloApp.getInstance().getApplication(),
                            downloadEntity.getPath()), downloadEntity.getUrl());

                    // 用户焦点在下载管理页面时有任务完成，直接把所有下载完成的任务标记为已读
                    DownloadManager.getInstance().markDownloadedTaskAsRead();
                } else if (DownloadStatus.cancel.equals(downloadEntity.getStatus())) { // 有可能由于网络劫持造成的
                    adapter.initMap();
                    adapter.notifyDataSetChanged();
                    int listSize = adapter.getDownloadingList().size() + adapter.getDoneList().size();
                    if (listSize == 0) {
                        EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, listSize));
                        if (mBinding.reuseNoneData.getRoot().getVisibility() == View.GONE) {
                            mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
                        }
                    } else {
                        EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                                adapter.getDownloadingList().size()));
                    }
                } else {
                    location = adapter.getLocation(downloadEntity.getUrl());
                    if (location != null && adapter.getDownloadingList().size() > location) {
                        adapter.getDownloadingList().set(location, downloadEntity);
                        adapter.notifyItemChanged(adapter.getBase() + location + 1);
                    }
                }
                if (downloadEntity.getStatus() == DownloadStatus.neterror
                        || downloadEntity.getStatus() == DownloadStatus.diskisfull
                        || downloadEntity.getStatus() == DownloadStatus.diskioerror) {
                    adapter.notifyItemChanged(adapter.getBase());
                }
            } else {
                if (!adapter.getDeleteList().contains(downloadEntity.getUrl())) {
                    DownloadStatus status = downloadEntity.getStatus();
                    if (status.equals(DownloadStatus.downloading)
                            || status.equals(DownloadStatus.waiting)
                            || status.equals(DownloadStatus.subscribe)) {
                        // 静默更新任务,下载模拟器任务,畅玩游戏不需要添加
                        if (ExtensionsKt.isSilentUpdate(downloadEntity)
                                || ExtensionsKt.isSimulatorDownload(downloadEntity)
                                || ExtensionsKt.isVGame(downloadEntity)) {
                            return;
                        }

                        if (adapter.getDownloadingList().isEmpty()) {
                            adapter.getDownloadingList().add(0, downloadEntity);
                            adapter.initLocationMap();
                            adapter.notifyItemRangeInserted(adapter.getBase(), 2);
                            if (mBinding.reuseNoneData.getRoot().getVisibility() == View.VISIBLE) {
                                mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
                            }
                            EventBus.getDefault().post(new EBDownloadChanged("download",
                                    View.VISIBLE, adapter.getDownloadingList().size()));
                        } else {
                            adapter.getDownloadingList().add(0, downloadEntity);
                            adapter.initLocationMap();
                            adapter.notifyItemInserted(adapter.getBase() + 1);
                            adapter.notifyItemChanged(adapter.getBase());
                            EventBus.getDefault().post(new EBDownloadChanged("download",
                                    View.VISIBLE, adapter.getDownloadingList().size()));
                        }
                    }
                }
            }

            if (location != null && XapkUnzipStatus.FAILURE.name().equals(downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS))) {
                XapkDialogHelper.INSTANCE.showUnzipFailureDialog(requireContext(), downloadEntity, false);
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected View getInflatedLayout() {
        mBinding = DownloadmanagerBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        String path = getActivity().getIntent().getStringExtra(EntranceConsts.KEY_PATH);
        url = getActivity().getIntent().getStringExtra(EntranceConsts.KEY_URL);

        isScroll = false;

        rparams = (RelativeLayout.LayoutParams) mBinding.downloadmanagerHeadContainer.getLayoutParams();

        mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
        ViewGroup.LayoutParams layoutParam = mBinding.reuseNoneData.reuseResetLoadTv.getLayoutParams();
        layoutParam.width = DisplayUtils.dip2px(150F);
        mBinding.reuseNoneData.reuseResetLoadTv.setLayoutParams(layoutParam);
        mBinding.reuseNoneData.reuseNoneDataTv.setText(getString(R.string.game_no_data));
        mBinding.reuseNoneData.reuseNoneDataDescTv.setVisibility(View.VISIBLE);
        mBinding.reuseNoneData.reuseNoneDataDescTv.setText(getString(R.string.game_no_data_desc));
        mBinding.reuseNoneData.reuseResetLoadTv.setText("去首页看看");
        mBinding.reuseNoneData.reuseResetLoadTv.setVisibility(View.VISIBLE);
        mBinding.reuseNoneData.reuseResetLoadTv.setOnClickListener(v -> MainActivity.skipToMainActivity(getActivity(), MainWrapperFragment.INDEX_HOME));
        mBinding.downloadingHintContainer.setOnClickListener(v -> mBinding.downloadmanagerRvShow.scrollToPosition(adapter.getItemCount() - 1));

        mBinding.downloadmanagerRvShow.setHasFixedSize(true);
        adapter = new GameDownloadFragmentAdapter(getActivity(), (LinearLayout) mBinding.reuseNoneData.getRoot(), url);
        mBinding.downloadmanagerRvShow.setAdapter(adapter);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.downloadmanagerRvShow.setLayoutManager(layoutManager);
        ((DefaultItemAnimator) mBinding.downloadmanagerRvShow.getItemAnimator()).setSupportsChangeAnimations(false);
        mBinding.downloadmanagerRvShow.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int position = layoutManager.findFirstVisibleItemPosition();
                if (adapter.getDoneList().isEmpty()) {
                    if (position >= 0) {
                        mBinding.downloadmanagerHeadContainer.setVisibility(View.VISIBLE);
                        mBinding.downloadmanagerTvTask.setText(R.string.downloading);
                        mBinding.downloadmanagerTvAllstart.setVisibility(View.VISIBLE);
                    } else {
                        mBinding.downloadmanagerHeadContainer.setVisibility(View.GONE);
                    }
                } else {
                    if (position >= 0 && position <= adapter.getDoneList().size()) {
                        mBinding.downloadmanagerHeadContainer.setVisibility(View.VISIBLE);
                        mBinding.downloadmanagerTvTask.setText("已完成");
                        mBinding.downloadmanagerTvAllstart.setVisibility(View.GONE);
                    } else if (position >= adapter.getDoneList().size() + 1) {
                        mBinding.downloadmanagerHeadContainer.setVisibility(View.VISIBLE);
                        mBinding.downloadmanagerTvTask.setText(R.string.downloading);
                        mBinding.downloadmanagerTvAllstart.setVisibility(View.VISIBLE);
                    } else {
                        mBinding.downloadmanagerHeadContainer.setVisibility(View.GONE);
                    }
                }

                if (adapter.getDoneList().size() != 0
                        && position == adapter.getDoneList().size()) {
                    int bottom = layoutManager.findViewByPosition(position).getBottom();
                    if (bottom <= mBinding.downloadmanagerHeadContainer.getHeight()) {
                        rparams.topMargin = bottom - mBinding.downloadmanagerHeadContainer.getHeight();
                        mBinding.downloadmanagerHeadContainer.setLayoutParams(rparams);
                    } else {
                        rparams.topMargin = 0;
                        mBinding.downloadmanagerHeadContainer.setLayoutParams(rparams);
                    }
                } else {
                    rparams.topMargin = 0;
                    mBinding.downloadmanagerHeadContainer.setLayoutParams(rparams);
                }
                showScrollToDownloadContainerIfNeeded();
            }
        });
        mBinding.downloadmanagerRvShow.setOnDispatchTouchListener((v, event) -> {
            if (url != null && event.getAction() == MotionEvent.ACTION_DOWN) {
                url = null;
                adapter.setUrl(null);
            }
        });

        if (path != null) {
            adapter.showPluginDialog(path);
        }
        mBinding.downloadmanagerTvAllstart.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.initMap();
        DownloadManager.getInstance().addObserver(dataWatcher);
        adapter.notifyDataSetChanged();
        showScrollToDownloadContainerIfNeeded();

        if (adapter.getDownloadingList().isEmpty() && adapter.getDoneList().isEmpty()) {
            mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
        } else {
            mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
        }
        if (url != null && !isScroll) {
            for (int i = 0, size = adapter.getDoneList().size(); i < size; i++) {
                if (adapter.getDoneList().get(i).getUrl().equals(url)) {
                    mBinding.downloadmanagerRvShow.scrollToPosition(i + 1);
                    isScroll = true;
                    return;
                }
            }
            for (int i = 0, size = adapter.getDownloadingList().size(); i < size; i++) {
                if (adapter.getDownloadingList().get(i).getUrl().equals(url)) {
                    mBinding.downloadmanagerRvShow.scrollToPosition(adapter.getBase() + i + 1);
                    isScroll = true;
                    return;
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        DownloadManager.getInstance().removeObserver(dataWatcher);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBMiPush mipush) {
        if ("plugin_install".equals(mipush.getFrom())) {
            String path = (String) mipush.getObj();
            adapter.showPluginDialog(path);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBPackage busFour) {
        String packageName = busFour.getPackageName();
        String url = adapter.getUrl(packageName);
        if (url != null) {
            Integer location = adapter.getLocation(url);
            if (location != null && EBPackage.TYPE_INSTALLED.equals(busFour.getType())) {
                if (adapter.getDownloadingList().isEmpty() && adapter.getDoneList().size() == 1) {
                    adapter.getDoneList().remove(location.intValue());
                    adapter.getLocationMap().clear();
                    adapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, 0));
                    if (mBinding.reuseNoneData.getRoot().getVisibility() == View.GONE) {
                        mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
                    }
                } else if (adapter.getDoneList().size() == 1) {
                    adapter.getDoneList().remove(location.intValue());
                    adapter.initLocationMap();
                    adapter.notifyItemRangeRemoved(0, 2);
                    EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                            adapter.getDownloadingList().size()));
                } else {
                    adapter.getDoneList().remove(location.intValue());
                    adapter.initLocationMap();
                    adapter.notifyItemRemoved(location + 1);
                    EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                            adapter.getDownloadingList().size()));
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBUISwitch busNine) {
        if (DownloadManagerActivity.TAG.equals(busNine.getFrom())) {
            if (busNine.getPosition() != 0) {
                adapter.getDeleteList().clear();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.downloadmanager_tv_allstart) {
            String str = ((TextView) v).getText().toString();
            if ("全部开始".equals(str)) {
                if (NetworkUtils.isWifiConnected(getActivity())) {
                    startAll();
                } else {
                    DialogHelper.showDownloadDialog(requireContext(), this::startAll);
                }
            } else {
                pauseAll();
            }

//            DataUtils.onMtaEvent(HaloApp.getInstance().getApplication(), "下载管理", "游戏下载", str);
            adapter.notifyItemChanged(adapter.getBase());
        }
    }

    public void pauseAll() {
        for (DownloadEntity downloadEntity : adapter.getDownloadingList()) {
            DownloadManager.getInstance().put(downloadEntity.getUrl(),
                    System.currentTimeMillis());
            Message msg = Message.obtain();
            msg.what = DownloadConfig.PAUSE_DOWNLOAD_TASK;
            msg.obj = downloadEntity.getUrl();
            DownloadManager.getInstance().sendMessageDelayed(msg, 1000);
//            DownloadManager.getInstance(getContext()).pause(downloadEntity);
        }
        DownloadManager.getInstance().pauseAll();
        mBinding.downloadmanagerTvAllstart.setText("全部开始");
        mBinding.downloadmanagerTvAllstart.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_font));
    }

    private void startAll() {
        for (DownloadEntity downloadEntity : adapter.getDownloadingList()) {
//            DownloadManager.getInstance(getContext()).add(downloadEntity);
//            adapter.getStatusMap().put(downloadEntity.getUrl(), "downloading");

            DownloadManager.getInstance().put(downloadEntity.getUrl(),
                    System.currentTimeMillis());
            Message msg = Message.obtain();
            msg.what = DownloadConfig.CONTINUE_DOWNLOAD_TASK;
            msg.obj = downloadEntity.getUrl();
            DownloadManager.getInstance().sendMessageDelayed(msg, 1000);
            adapter.getStatusMap().put(downloadEntity.getUrl(), "downloading");
        }
//        DownloadManager.getInstance(getContext()).startAll();
        mBinding.downloadmanagerTvAllstart.setText("全部暂停");
        mBinding.downloadmanagerTvAllstart.setTextColor(ContextCompat.getColor(getContext(), R.color.btn_gray));
    }

    private void showScrollToDownloadContainerIfNeeded() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) mBinding.downloadmanagerRvShow.getLayoutManager();
        if (layoutManager != null) {
            int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();

            if (adapter.getDownloadingList().size() != 0
                    && adapter.getDoneList().size() >= lastCompletelyVisibleItemPosition) {
                mBinding.downloadingHintContainer.setVisibility(View.VISIBLE);
            } else {
                mBinding.downloadingHintContainer.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        mBinding.downloadmanagerRvShow.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
        mBinding.downloadingContainer.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
        mBinding.downloadmanagerHeadContainer.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
        mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.text_title));
        mBinding.reuseNoneData.reuseNoneDataDescTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.text_subtitleDesc));
        mBinding.reuseNoneData.reuseNoneDataIv.setImageResource(R.drawable.ic_empty_data);
        adapter.notifyItemRangeChanged(0, adapter.getItemCount());
    }
}
