import { StrUtil } from '@pura/harmony-utils' import { VideoItem } from '../../viewmodel/VideoItem' export enum QueueInsertStatus { INVALID_SONG = 0, START_PLAY = 1, INSERTED = 2, ALREADY_PLAYING = 3 } export interface QueueInsertResult { status: QueueInsertStatus queue: VideoItem[] currentIndex: number insertedIndex: number } function resolveCurrentQueueIndex(queue: VideoItem[], currentFilePath: string, fallbackIndex: number): number { if (queue.length <= 0) { return -1 } if (StrUtil.isNotEmpty(currentFilePath)) { const queueIndex = queue.findIndex((item: VideoItem) => item.filePath === currentFilePath) if (queueIndex >= 0) { return queueIndex } } if (fallbackIndex >= 0 && fallbackIndex < queue.length) { return fallbackIndex } return 0 } export function insertSongToNextPlayQueue(queue: VideoItem[], currentFilePath: string, fallbackIndex: number, song: VideoItem): QueueInsertResult { if (!song || StrUtil.isEmpty(song.filePath)) { return { status: QueueInsertStatus.INVALID_SONG, queue: queue.slice(), currentIndex: resolveCurrentQueueIndex(queue, currentFilePath, fallbackIndex), insertedIndex: -1 } } if (queue.length <= 0) { return { status: QueueInsertStatus.START_PLAY, queue: [song], currentIndex: 0, insertedIndex: 0 } } const nextQueue = queue.slice() let currentIndex = resolveCurrentQueueIndex(nextQueue, currentFilePath, fallbackIndex) const currentPath = currentIndex >= 0 && currentIndex < nextQueue.length ? nextQueue[currentIndex].filePath : '' if (song.filePath === currentPath) { return { status: QueueInsertStatus.ALREADY_PLAYING, queue: nextQueue, currentIndex, insertedIndex: currentIndex } } const existingIndex = nextQueue.findIndex((item: VideoItem) => item.filePath === song.filePath) if (existingIndex >= 0) { const movedSong = nextQueue.splice(existingIndex, 1)[0] if (existingIndex < currentIndex) { currentIndex -= 1 } nextQueue.splice(currentIndex + 1, 0, movedSong) } else { nextQueue.splice(currentIndex + 1, 0, song) } return { status: QueueInsertStatus.INSERTED, queue: nextQueue, currentIndex, insertedIndex: currentIndex + 1 } }