//
// © 2017-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import Foundation

struct PersistedAllUserFavorites: Codable {
    var items: [PersistedMediaItem] = []
}

class FavoritesController {
	enum FavoritesControllerError: Error {
		case outOfBounds
	}
	
    public static let sharedInstance = FavoritesController()
	private lazy var favorites: PersistedAllUserFavorites = {
		guard let i: PersistedAllUserFavorites = PersistenceController.load() else {
			return PersistedAllUserFavorites()
		}
		return i
	} ()
}

// MARK: - Public Methods
extension FavoritesController {
	var allFavorites: [IoTMediaItem] {
		let mediaItems = favorites.items.compactMap { $0.mediaItem() }
		return mediaItems
	}
	
    public func haveFavorites() -> Bool {
        return favorites.items.count != 0
    }
    
    public func isFavorite(item: IoTMediaItem) -> Bool {
        return favorites.items.contains{ return $0.represents(mediaItem: item) }
    }
	
	public func isFavoritable(item: IoTMediaItem) -> Bool {
		return HTTPServer.sharedInstance.isLocalAssetURL(item.streamURL)
	}
    
    public func makeFavorite(item: IoTMediaItem) {
        if !isFavorite(item: item) {
            let persisted = PersistedMediaItem(item: item)
            favorites.items.insert(persisted, at: 0)
            PersistenceController.store(favorites)
        }
    }
    
    public func removeFavorite(item: IoTMediaItem) {
		if let idx = favorites.items.firstIndex(where: { return $0.represents(mediaItem: item) }) {
            favorites.items.remove(at: idx)
            PersistenceController.store(favorites)
        }
    }
	
	public func moveFavorite(from: Int, to: Int) throws {
		guard from < favorites.items.count, to < favorites.items.count else {
			throw FavoritesControllerError.outOfBounds
		}
		
		let item = favorites.items[from]
		let myTo = (from > to) ? to : (to - 1)
		favorites.items.remove(at: from)
		favorites.items.insert(item, at: myTo)
		PersistenceController.store(favorites)
	}
	
	public func removeAll() {
		favorites.items = []
		PersistenceController.store(favorites)
	}
}
