import {
	isBackgroundPlaybackEnabled,
	setBackgroundPlaybackEnabled
} from '@/features/feed/background-playback-settings'

export { isBackgroundPlaybackEnabled, setBackgroundPlaybackEnabled }

let appInBackground = false

export function markAppInBackground(value) {
	appInBackground = !!value
}

export function isAppInBackground() {
	return appInBackground
}

/** 页面 onHide 时是否应保持 Feed 播放（仅 App 切后台且开关开启） */
export function shouldKeepFeedPlaybackOnPageHide() {
	return appInBackground && isBackgroundPlaybackEnabled()
}

export function applyBackgroundPlaybackSession(active) {
	// #ifdef APP-PLUS
	if (!active) {
		resetIosPlaybackSession()
		return
	}
	if (!isBackgroundPlaybackEnabled()) return
	try {
		const os = String(plus.os.name || '').toLowerCase()
		if (os === 'ios') {
			enableIosPlaybackSession()
		}
	} catch (e) {
		console.warn('[background-playback] apply session', e)
	}
	// #endif
}

// #ifdef APP-PLUS
function enableIosPlaybackSession() {
	const AVAudioSession = plus.ios.import('AVAudioSession')
	const session = AVAudioSession.sharedInstance()
	try {
		session.setCategory('AVAudioSessionCategoryPlayback', null)
		session.setActive(true, null)
	} finally {
		plus.ios.deleteObject(session)
		plus.ios.deleteObject(AVAudioSession)
	}
}

function resetIosPlaybackSession() {
	const AVAudioSession = plus.ios.import('AVAudioSession')
	const session = AVAudioSession.sharedInstance()
	try {
		session.setActive(false, null)
	} catch (_) {
	} finally {
		plus.ios.deleteObject(session)
		plus.ios.deleteObject(AVAudioSession)
	}
}
// #endif
