//
//  AudioBookDetailsVC.swift
//  WOKA
//
//  Created by MacBook Pro on 03/07/24.
//

import UIKit

class AudioBookDetailsVC : UIViewController{
    
    @IBOutlet weak var watchingImage: UIImageView!
    @IBOutlet weak var watchingTitle: UILabel!
    @IBOutlet weak var watchingDesc: UITextView!
    
    @IBOutlet weak var addIcon: UIImageView!
    @IBOutlet weak var addLabel: UILabel!
    @IBOutlet weak var likeIcon: UIImageView!
    @IBOutlet weak var likeLabel: UILabel!
    @IBOutlet weak var totalLikes: UILabel!
    
    @IBOutlet weak var addView: UIView!
    @IBOutlet weak var shareView: UIView!
    @IBOutlet weak var likeView: UIView!
    
    @IBOutlet weak var outerView: UIView!
    @IBOutlet weak var contentView: UIView!
    
    var delegate : ReloadSeriesFavLike?
    
    var audioData : ListenAudioListingDM.AudioDatum?
    
//    var continueAudioData : ListenAudioListingDM.AudioDatum?
    var audioIndex = 0
    
    typealias btnTappedBlock = ( _ from : FavCellCLick) -> Void
    var btnTapped : btnTappedBlock?
    var reloadType : FavCellCLick?

    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        
        self.view.addTapGesture {
            self.dismiss(animated: true)
        }
        
        tapHandler()
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: outerView)
        if !contentView.frame.contains(location) {
            if let postID = audioData?.id{
                PersistentStorage.shared.addAudioCount(postID: postID)
            }
            
            if let reloadType{
                if btnTapped != nil {
                    btnTapped?(reloadType)
                }
            }
            
            self.dismiss(animated: true)
        }
    }
    
    func tapHandler(){
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        outerView.addGestureRecognizer(tapGesture)
        
        addView.addTapGesture { [weak self] in
            guard let self else{return}
            if let postID = audioData?.id{
                PersistentStorage.shared.addAudioCount(postID: postID)
            }
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

            if let audioData{
                guard let showID = audioData.id, let isFav = audioData.markAsFavourite, let postType = audioData.contentMoreDetails?.first?.postType else{return}

                if isFav {
                    LikeFavCommonFunc.shareInstance.removeFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.audioData?.markAsFavourite = false
                        
//                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.audioData?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
                        
                        K.GVar.reloadMyListAudioBooks = true
                        self.reloadType = .favourite
                        self.delegate?.updateRows(index: self.audioIndex, type: .favourite, isFav: false, isLike: nil, id: showID)
                        self.initView()
                    }
                }else{
                    LikeFavCommonFunc.shareInstance.addFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.audioData?.markAsFavourite = true
                        
//                        if let audioData = self.audioData{
//                            MyListDataTemp.shareInstance.favListingData?.audioData?.append(audioData)
//                            K.GVar.myListSoftReload = true
//                        }
                        
                        K.GVar.reloadMyListAudioBooks = true
                        self.reloadType = .favourite
                        self.delegate?.updateRows(index: self.audioIndex, type: .favourite, isFav: true, isLike: nil, id: showID)
                        self.initView()
                    }
                }
            }
            
//            if let continueAudioData{
//                guard  let showID = continueAudioData.id, let isFav = continueAudioData.markAsFavourite, let postType = continueAudioData.contentMoreDetails?.first?.postType else{return}
//
//                if isFav {
//                    LikeFavCommonFunc.shareInstance.removeFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
//                        self.continueAudioData?.markAsFavourite = false
//                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.audioData?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
//                        self.delegate?.updateRows(index: self.audioIndex, type: .favourite, isFav: false, isLike: nil, id: showID)
//                        self.initView()
//                    }
//                }else{
//                    LikeFavCommonFunc.shareInstance.addFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
//                        self.continueAudioData?.markAsFavourite = true
//                        if let audioData = self.audioData{
//                            if MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}) == nil{
//                                MyListDataTemp.shareInstance.favListingData?.audioData?.append(audioData)
//                                K.GVar.myListSoftReload = true
//                            }
//                        }
//                        self.delegate?.updateRows(index: self.audioIndex, type: .favourite, isFav: true, isLike: nil, id: showID)
//                        self.initView()
//                    }
//                }
//            }
        }
        
        likeView.addTapGesture { [weak self] in
            
            guard let self else{return}
            if let postID = audioData?.id{
                PersistentStorage.shared.addAudioCount(postID: postID)
            }
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

            if let audioData{
                guard let showID = audioData.id, let isLiked = audioData.isLiked, let postType = audioData.contentMoreDetails?.first?.postType else{return}

                if isLiked{
                    LikeFavCommonFunc.shareInstance.unlikePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.audioData?.isLiked = false
                        self.audioData?.likesCount! -= 1
                        
                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! -= 1
                            K.GVar.myListSoftReload = true
                        }
                        self.reloadType = .favourite
                        self.delegate?.updateRows(index: self.audioIndex, type: .liked, isFav: nil, isLike: false, id: showID)
                        self.initView()
                    }
                }else{
                    LikeFavCommonFunc.shareInstance.likePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.audioData?.isLiked = true
                        self.audioData?.likesCount! += 1
                        
                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! += 1
                            K.GVar.myListSoftReload = true
                        }
                        self.reloadType = .favourite
                        self.delegate?.updateRows(index: self.audioIndex, type: .liked, isFav: nil, isLike: true, id: showID)
                        self.initView()
                    }
                }
            }
            
//            if let continueAudioData{
//                guard let showID = continueAudioData.id, let isLiked = continueAudioData.isLiked, let postType = continueAudioData.contentMoreDetails?.first?.postType else{return}
//
//                if isLiked{
//                    LikeFavCommonFunc.shareInstance.unlikePost(postID: showID, postType: postType, vc: self) { isDone in
//                        self.continueAudioData?.isLiked = false
//                        if self.audioData?.likesCount != nil{
//                            self.audioData?.likesCount! -= 1
//                        }
//                        
//                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = false
//                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! -= 1
//                            K.GVar.myListSoftReload = true
//                        }
//                        
//                        self.delegate?.updateRows(index: self.audioIndex, type: .liked, isFav: nil, isLike: false, id: showID)
//                        self.initView()
//                    }
//                }else{
//                    LikeFavCommonFunc.shareInstance.likePost(postID: showID, postType: postType, vc: self) { isDone in
//                        self.continueAudioData?.isLiked = true
//                        if self.audioData?.likesCount != nil{
//                            self.audioData?.likesCount! += 1
//                        }
//                        
//                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = true
//                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! += 1
//                            K.GVar.myListSoftReload = true
//                        }
//                        
//                        self.delegate?.updateRows(index: self.audioIndex, type: .liked, isFav: nil, isLike: true, id: showID)
//                        self.initView()
//                    }
//                }
//            }
            
        }
        
        shareView.addTapGesture { [weak self] in
            guard let self else{return}
            if let postID = audioData?.id{
                PersistentStorage.shared.addAudioCount(postID: postID)
            }
            
            if let name = URL(string: "https://apps.apple.com/in/app/woka/id6465305185"), !name.absoluteString.isEmpty {
              let objectsToShare = [name]
              let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
                self.present(activityVC, animated: true, completion: nil)
            } else {
              // show alert for not available
            }
        }
    }
    
    func initView(){
        if let audioData{
            if let url = audioData.thumbnailPath{
                watchingImage.imageURL(url, color: .white)
            }
            
            totalLikes.text = audioData.likesCount?.toString() ?? "0"
            if let like = audioData.isLiked{
                switch like{
                case true:
                    likeIcon.image = UIImage(systemName: "hand.thumbsup.fill")
                    likeLabel.text = "LIKED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                case false:
                    likeIcon.image = UIImage(systemName: "hand.thumbsup")
                    likeLabel.text = "LIKE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }
            }
            
            if let favourite = audioData.markAsFavourite{
                if favourite == true{
                    addIcon.image = UIImage(systemName: "heart.fill")
                    addLabel.text = "ADDED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }else{
                    addIcon.image = UIImage(systemName: "heart")
                    addLabel.text = "ADD".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }
            }
            
            if AuthFunc.shareInstance.getDefaultLanguage() == .english{
                if let englishData = audioData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first{
                    watchingTitle.text = englishData.title
                    if let desc = englishData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                        let sizeText = NSMutableAttributedString(attributedString: desc)
                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                        self.watchingDesc.attributedText = sizeText
                    }
                }
            }else{
                if let hindiData = audioData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first{
                    watchingTitle.text = hindiData.title
                    if let desc = hindiData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                        let sizeText = NSMutableAttributedString(attributedString: desc)
                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                        self.watchingDesc.attributedText = sizeText
                    }
                }
            }
        }
        
//        if let continueAudioData{
//            if let url = continueAudioData.thumbnailPath{
//                watchingImage.imageURL(url, color: .white)
//            }
//            
//            totalLikes.text = continueAudioData.likesCount?.toString() ?? "0"
//            if let like = continueAudioData.isLiked{
//                switch like{
//                case true:
//                    likeIcon.image = UIImage(systemName: "hand.thumbsup.fill")
//                    likeLabel.text = "LIKED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//                case false:
//                    likeIcon.image = UIImage(systemName: "hand.thumbsup")
//                    likeLabel.text = "LIKE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//                }
//            }
//            
//            if let favourite = continueAudioData.markAsFavourite{
//                if favourite == true{
//                    addIcon.image = UIImage(systemName: "heart.fill")
//                    addLabel.text = "ADDED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//                }else{
//                    addIcon.image = UIImage(systemName: "heart")
//                    addLabel.text = "ADD".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//                }
//            }
//            
//            if AuthFunc.shareInstance.getDefaultLanguage() == .english{
//                if let englishData = continueAudioData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first{
//                    watchingTitle.text = englishData.title
//                    if let desc = englishData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
//                        let sizeText = NSMutableAttributedString(attributedString: desc)
//                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
//                        self.watchingDesc.attributedText = sizeText
//                    }
//                }
//            }else{
//                if let hindiData = continueAudioData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first{
//                    watchingTitle.text = hindiData.title
//                    if let desc = hindiData.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
//                        let sizeText = NSMutableAttributedString(attributedString: desc)
//                        sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
//                        self.watchingDesc.attributedText = sizeText
//                    }
//                }
//            }
//        }
    }
    
    @IBAction func watchBtnTapped(_ sender: LocalisedElementsButton) {
        var playerItems = [JwPlayerItemCreate]()

        if let audioData{
            if AuthFunc.shareInstance.getDefaultLanguage() == .english{
                if let englishData = audioData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let url = englishData.url{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: audioData.thumbnailPath, titles: englishData.title))
                }
            }else{
                if let hindiData = audioData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first, let url = hindiData.url{
                    playerItems.append(JwPlayerItemCreate(url: url, poster: audioData.thumbnailPath, titles: hindiData.title))
                }
            }
        }
        
//        if let continueAudioData{
//            if AuthFunc.shareInstance.getDefaultLanguage() == .english{
//                if let englishData = continueAudioData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first, let url = englishData.url{
//                    playerItems.append(JwPlayerItemCreate(url: url, poster: continueAudioData.thumbnailPath, titles: englishData.title))
//                }
//            }else{
//                if let hindiData = continueAudioData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first, let url = hindiData.url{
//                    playerItems.append(JwPlayerItemCreate(url: url, poster: continueAudioData.thumbnailPath, titles: hindiData.title))
//                }
//            }
//        }
        if let audioID = audioData?.id{
            JWPlayerManager.shared.presentPlayer(from: self, playerItems: playerItems, startIndex: 0, contentType: .audioBooks,videoIDs: [audioID])
        }
    }
    
    @IBAction func closeBtnTapped(_ sender: UIButton) {
        if let postID = audioData?.id{
            PersistentStorage.shared.addAudioCount(postID: postID)
        }
        if let reloadType{
            if btnTapped != nil {
                btnTapped?(reloadType)
            }
        }
        self.dismiss(animated: true)
    }
}
