//
//  PlayerVM.swift
//  WOKA
//
//  Created by Bilal on 16/08/2024.
//

import UIKit

class PlayerVM{
    
    weak var vc : PlayerVC!
    
    // this will map the start time
    var startTimeStamp = Date()
    var totalVideoViewTime = 0
    
    // this will come from webseries, audiobooks, live tv
    var videoIDs = [Int]()
    
    // this will come only for webseries
    var catID : Int?
    
    // this will store the index of the item playing
    var currentPlayingIndex = -1

    func initView(){
        switch vc.contentType {
        case .liveStream, .trailer, .continueWatching, .audioBooks:
            startTimeStamp = Date()
//        case .games:
//            <#code#>
//        case .songs:
//            <#code#>
        case nil:
            break
        default:
            break
        }
    }
    
    // MARK: - Update UserVideo View
    
    func updateUserView(){
        switch vc.contentType {
        case .liveStream:
            if let postID = videoIDs.first {
                let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
                let totalDuration = duration + totalVideoViewTime
                startTimeStamp = Date()
                AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.liveTV.rawValue, duration: totalDuration, catID: 0) { isDone in
                    if isDone{
                        K.GVar.reloadContinueAudioBooks = true
                    }else{
                        
                    }
                }
            }
        case .webSeries:
            if let catID = catID, currentPlayingIndex >= 0 && currentPlayingIndex < (videoIDs.count - 1) {
                let postID = videoIDs[currentPlayingIndex]
                let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
                let totalDuration = duration + totalVideoViewTime
                startTimeStamp = Date()
                AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.episode.rawValue, duration: totalDuration, catID: catID) { isDone in
                    if isDone{
                        K.GVar.reloadContinueWebSeries = true
                    }
                }
            }
        case .trailer:
            let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
            let totalDuration = duration + totalVideoViewTime
            AuthFunc.shareInstance.userVideoView(postID: 0, postType: PostType.episode.rawValue, duration: totalDuration, catID: 0) { _ in}
        case .continueWatching:
            if let catID = catID , let postID = videoIDs.first{
                let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
                let totalDuration = duration + totalVideoViewTime
                startTimeStamp = Date()
                AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.episode.rawValue, duration: totalDuration, catID: catID) { isDone in
                    if isDone{
                        K.GVar.reloadContinueWebSeries = true
                    }
                }
            }
        case .audioBooks:
            if let postID = videoIDs.first {
                let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
                let totalDuration = duration + totalVideoViewTime
                startTimeStamp = Date()
                AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.audio.rawValue, duration: totalDuration, catID: 0) { isDone in
                    if isDone{
                        K.GVar.reloadContinueAudioBooks = true
                    }else{
                        
                    }
                }
            }
//        case .games:
//            <#code#>
//        case .songs:
//            <#code#>
        case nil:
            break
        default:
            break
        }
        
    }

    
    // MARK: - Handle Back btn tap, and update clicks

    func handleBackAction(){
        self.vc.interfaceBehavior = .hidden
        self.vc.player.stop()
        if vc.contentType == .liveStream{
            self.vc.dismissTapped?()
        }
        updateClicks()

        DispatchQueue.main.async {
            if #available(iOS 16.0, *) {
                // Code for iOS 15.0 and above
                appDelegate.deviceOrientation = .portrait
                let value = UIInterfaceOrientation.portrait.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            } else {
                // Fallback code for earlier iOS versions
                self.vc.dismiss(animated: true)
            }
        }
    }
    
    func updateClicks(){
        switch vc.contentType {
        case .liveStream:
            PersistentStorage.shared.addLiveTVCount()
//        case .webSeries:
////            PersistentStorage.shared.addOthersCount()
        case .trailer:
            PersistentStorage.shared.addTrailerCount()
//        case .continueWatching:
//            <#code#>
//        case .audioBooks:
//            <#code#>
//        case .games:
//            <#code#>
//        case .songs:
//            <#code#>
        case nil:
            break
        default:
            break
        }
    }
    
    // MARK: - Orientation check
    
    func checkOrientation() {
        let isPortrait = UIScreen.main.bounds.size.width < UIScreen.main.bounds.size.height
        if isPortrait {
            print("Device is in portrait mode")
            Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) { _ in
                self.vc.dismiss(animated: true)
            }
        } else {
            print("Device is in landscape mode")
            if vc.isFullScreenBtn{
                DispatchQueue.main.async {
                    appDelegate.deviceOrientation = .portrait
                    
                    let value = UIInterfaceOrientation.portrait.rawValue
                    UIDevice.current.setValue(value, forKey: "orientation")
                    UIViewController.attemptRotationToDeviceOrientation()
                }
            }
        }
    }

}
