/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.horologist.media3.audio

import com.google.android.horologist.audio.AudioOutput
import com.google.android.horologist.audio.AudioOutputRepository
import com.google.android.horologist.media3.ExperimentalHorologistMedia3BackendApi
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull

/**
 * Implementation of audio output selection using bluetooth settings fragment
 * and waiting up to 15 seconds for a new output to be available.
 */
@ExperimentalHorologistMedia3BackendApi
public class BluetoothSettingsOutputSelector(
    private val audioOutputRepository: AudioOutputRepository
) : AudioOutputSelector {
    override suspend fun selectNewOutput(currentAudioOutput: AudioOutput): AudioOutput? {
        audioOutputRepository.launchOutputSelection()

        val newAudioOutput = withTimeoutOrNull(15000) {
            audioOutputRepository.audioOutput.filter {
                it != AudioOutput.None && it != currentAudioOutput
            }.first()
        }

        return newAudioOutput
    }

    override fun launchSelector() {
        audioOutputRepository.launchOutputSelection()
    }
}
