//
//  JWPlayerManager.swift
//  WOKA
//
//  Created by MacBook Pro on 24/06/24.
//

import UIKit
import JWPlayerKit

enum VideoContentType{
    case liveStream
    case webSeries
    case trailer
    case masilaSongs
    case continueWatching
    case audioBooks
    case games
    case songs
}

struct JwPlayerItemCreate{
    var url : String
    var poster : String?
    var titles : String?
}

class JWPlayerManager {
    static let shared = JWPlayerManager()

    private init() {}

    func presentPlayer(from viewController: UIViewController,playerItems : [JwPlayerItemCreate], startIndex: Int = 0, contentType : VideoContentType , videoIDs : [Int],catID : Int? = nil, completion: (() -> Void)? = nil) {

        let sb = UIStoryboard(name: K.StoryBoard.theme, bundle: nil)
        let playerVC = sb.instantiateViewController(identifier: K.StoryBoardID.Theme.playerVC) as! PlayerVC

            do {
                // Create an array to hold the JWPlayerItems
                var items: [JWPlayerItem] = []

                // Ensure the liveStreamURLs and titles arrays have the same count, if titles are provided
//                if let titles = titles, titles.count != liveStreamURLs.count {
//                    print("Titles count does not match URLs count")
//                    Utilities.dismissProgressHUD()
//                    return
//                }

                switch contentType{
                case .webSeries,.songs, .masilaSongs:
                    // Iterate over the liveStreamURLs to create JWPlayerItems
                    for (index, singleItem) in playerItems.enumerated() {
                        guard let url = URL(string: singleItem.url) else {
                            print("Invalid live stream URL at index \(index)")
                            continue
                        }
                        
                        let item = try JWPlayerItemBuilder()
                            .file(url)
                            .title(singleItem.titles ?? "NA")
                            .posterImage(URL(string: singleItem.poster ?? "")!)
                            .build()

                        items.append(item)
                    }
                case .liveStream:
                    guard let liveStreamItem = playerItems.first else {
                        print("Invalid live stream URL")
                        return
                    }
                    
                    let item = try JWPlayerItemBuilder()
                        .file(URL(string: liveStreamItem.url)!)
                        .title(liveStreamItem.titles ?? "Trailer")
                        .build()
                    items.append(item)
                case .trailer:
                    guard let liveStreamItem = playerItems.first else {
                        print("Invalid live stream URL")
                        return
                    }
                    let item = try JWPlayerItemBuilder()
                        .file(URL(string: liveStreamItem.url)!)
                        .title(liveStreamItem.titles ?? "Trailer")
                        .build()
                    items.append(item)
                case .continueWatching, .audioBooks, .games:
                    guard let liveStreamItem = playerItems.first else {
                        print("Invalid live stream URL")
                        return
                    }
                    let item = try JWPlayerItemBuilder()
                        .file(URL(string: liveStreamItem.url)!)
                        .title(liveStreamItem.titles ?? "Trailer")
                        .build()
                    items.append(item)
                }
                

                // Ensure there is at least one valid item
                guard !items.isEmpty else {
                    print("No valid items to play")
                    Utilities.dismissProgressHUD()
                    return
                }
                
                // Create an ad break for 30% into the video
                let finalConfig : JWPlayerConfiguration?
                
                switch contentType{
                case .audioBooks:
                    finalConfig = try JWPlayerConfigurationBuilder()
                        .playlist(items: items)
                        .autostart(false)
                        .build()
                    //                    if let adConfigs = JWAdsBuilder.shareInstace.createAds(adsData: [ad1,ad2,ad3]){
                    //                        finalConfig = try JWPlayerConfigurationBuilder()
                    //                            .playlist(items: items)
                    //                            .autostart(true)
                    //                            .advertising(adConfigs)
                    //                            .build()
                    //                    }else{
                    //                        finalConfig = try JWPlayerConfigurationBuilder()
                    //                            .playlist(items: items)
                    //                            .autostart(true)
                    //                            .build()
                    //                    }
                case .webSeries:
                    finalConfig = try JWPlayerConfigurationBuilder()
                        .playlist(items: items)
                        .autostart(false)
                        .build()
                    //                    if let adsData = AuthFunc.shareInstance.adsData, let webSeriesVideoAd = adsData.result?.filter({$0.slug == AdsEnum.webSeriesVideoAd.rawValue}).first, webSeriesVideoAd.googleAd != nil, let adConfigs = JWAdsBuilder.shareInstace.createAds(adsData: [ad1, ad2, ad3]){
//                        finalConfig = try JWPlayerConfigurationBuilder()
//                            .playlist(items: items)
//                            .autostart(false)
//                            .advertising(adConfigs)
//                            .build()
//                    }else{
//                        finalConfig = try JWPlayerConfigurationBuilder()
//                            .playlist(items: items)
//                            .autostart(false)
//                            .build()
//                    }
                case .masilaSongs:
                    finalConfig = try JWPlayerConfigurationBuilder()
                        .playlist(items: items)
                        .autostart(true)
//                        .advertising(adConfigs!)
                        .build()
                case .trailer:
                    finalConfig = try JWPlayerConfigurationBuilder()
                        .playlist(items: items)
                        .autostart(true)
                        .build()
                default:
                    // Create a JWPlayerConfiguration with the playlist
                    finalConfig = try JWPlayerConfigurationBuilder()
                        .playlist(items: items)
                        .autostart(false)
                        .build()
                }
                
//                DispatchQueue.main.async {
                    playerVC.videoIndex = startIndex
                    playerVC.contentType = contentType
                    playerVC.config = finalConfig
                    playerVC.vm.videoIDs = videoIDs
                    playerVC.vm.catID = catID
                    playerVC.modalPresentationStyle = .fullScreen
                    playerVC.modalTransitionStyle = .crossDissolve
                    // Present the PlayerVC
                    Utilities.dismissProgressHUD()
                    viewController.present(playerVC, animated: true) {
                        if contentType == .webSeries{
                            playerVC.player.loadPlayerItemAt(index: startIndex)
                        }
                        completion?()
    //                    playerVC.transitionToFullScreen(animated: true) {
    //                        print("FullScreen")
    //                    }
                    }
//                }
            } catch {
                print("Error creating JWPlayer configuration: \(error)")
                Utilities.dismissProgressHUD()
            }
    }
}

