package com.gh.gamecenter.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.gh.gamecenter.common.constant.Constants;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.repository.ReservationRepository;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.halo.assistant.HaloApp;

import org.greenrobot.eventbus.EventBus;

// 监听网络状态的变化
public class NetworkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 网络变更这里会被主进程和推送进程分别调用，这里只对主进程响应，
        // 奇怪，初次注册监听就会有回调，会导致部分接口短时间内触发两次调用
        ExtensionsKt.doOnMainProcessOnly(context, () -> {
            if (NetworkUtils.isNetworkConnected(context)) {
                RegionSettingHelper.getRegionSetting();
                ReservationRepository.refreshReservationsIfNeeded();
                EventBus.getDefault().post(new EBNetworkState(NetworkUtils.isNetworkConnected(context)));
                DownloadManager.getInstance().checkAndRetryDownload();
                if (NetworkUtils.isMobileConnected(context)) {
                    HaloApp.put(Constants.SHOULD_SHOW_VIDEO_MOBILE_WARNING, true);
                }
            }
        });
    }
}
