//
//  GamesDetailVC.swift
//  WOKA
//
//  Created by MacBook Pro on 04/07/24.
//

import UIKit
import GoogleMobileAds
import Alamofire

class GamesDetailVC: 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 gameData : GamesListDM.GameDatum?
    var delegate : ReloadSeriesFavLike?
    var gameIndex = 0
    
    //for myList
    typealias btnTappedBlock = ( _ from : FavCellCLick) -> Void
    var btnTapped : btnTappedBlock?
    var reloadType : FavCellCLick?
    
    private var interstitial: GADInterstitialAd?
    private var rewardedAd: GADRewardedAd?
    
    let reachability = NetworkReachabilityManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        tapHandler()
        setupAds()
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: outerView)
        if !contentView.frame.contains(location) {
            if let postID = gameData?.id{
                PersistentStorage.shared.addGamesCount(postID: postID)
            }
            if let reloadType{
                if btnTapped != nil {
                    btnTapped?(reloadType)
                }
            }
            self.dismiss(animated: true)
        }
    }
    
    func initView(){
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        outerView.addGestureRecognizer(tapGesture)
        
        if let gameData{
            if let url = gameData.thumbnailPath{
                watchingImage.imageURL(url, color: .white)
            }
            
            totalLikes.text = gameData.likesCount?.toString() ?? "0"
            if let like = gameData.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 = gameData.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 = gameData.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 = gameData.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
                    }
                }
            }
        }
    }
    
    func tapHandler(){
        
        self.view.addTapGesture {
            self.dismiss(animated: true)
        }
        
        addView.addTapGesture { [weak self] in
            guard let self else{return}
            if let postID = gameData?.id{
                PersistentStorage.shared.addGamesCount(postID: postID)
            }
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}
            
            if let gameData{
                guard  let showID = gameData.id, let isFav = gameData.markAsFavourite, let postType = gameData.contentMoreDetails?.first?.postType else{return}

                if isFav {
                    //remove
                    LikeFavCommonFunc.shareInstance.removeFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.gameData?.markAsFavourite = false
//                        if let index = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.gameData?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
                        K.GVar.reloadGames = true
                        self.reloadType = .favourite
                        // To reload MyListViewAllVC
                        K.GVar.reloadMyListAll = 2
                        K.GVar.reloadMyListAllID = showID
                        
                        self.delegate?.updateRows(index: self.gameIndex, type: .favourite, isFav: false, isLike: nil, id: showID)
                        self.initView()
                    }
                }else{
                    //add
                    LikeFavCommonFunc.shareInstance.addFavourite(postID: showID, postType: postType, categoryID: 0, vc: self) { isDone in
                        self.gameData?.markAsFavourite = true
//                        if let gameData = self.gameData{
//                            MyListDataTemp.shareInstance.favListingData?.gameData?.append(gameData)
//                            K.GVar.myListSoftReload = true
//                        }
                        K.GVar.reloadGames = true
                        self.reloadType = .favourite
                        // To reload MyListViewAllVC
                        K.GVar.reloadMyListAll = 1
                        K.GVar.reloadMyListAllID = showID
                        
                        self.delegate?.updateRows(index: self.gameIndex, type: .favourite, isFav: true, isLike: nil, id: showID)
                        self.initView()
                    }
                }
            }
            
        }
        
        likeView.addTapGesture { [weak self] in
            guard let self else{return}
            if let postID = gameData?.id{
                PersistentStorage.shared.addGamesCount(postID: postID)
            }
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

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

                if isLiked{
                    //unlike
                    LikeFavCommonFunc.shareInstance.unlikePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.gameData?.isLiked = false
                        if let index = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.gameData?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.gameData?[index].likesCount! -= 1
                        }
                        self.delegate?.updateRows(index: self.gameIndex, type: .liked, isFav: nil, isLike: false, id: showID)
                        K.GVar.myListSoftReload = true
                        self.reloadType = .favourite
                        self.initView()
                    }
                }else{
                    //like
                    LikeFavCommonFunc.shareInstance.likePost(postID: showID, postType: postType, vc: self) { isDone in
                        self.gameData?.isLiked = true
                        if let index = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.gameData?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.gameData?[index].likesCount! += 1
                        }
                        self.delegate?.updateRows(index: self.gameIndex, type: .liked, isFav: nil, isLike: true, id: showID)
                        K.GVar.myListSoftReload = true
                        self.reloadType = .favourite
                        self.initView()
                    }
                }
            }
        }
        
        shareView.addTapGesture { [weak self] in
            guard let self else{return}
            if let postID = gameData?.id{
                PersistentStorage.shared.addGamesCount(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
            }
        }
    }
    
    @IBAction func playNowBtnTapped(_ sender: LocalisedElementsButton) {
        if let postID = gameData?.id{
            PersistentStorage.shared.addGamesCount(postID: postID)
        }
        
        /*
         check ad timestamp from gvar
         show ads if the saved timestamp time and current time has diffrenece of 30 minutes
         */
        if let timeStamp = K.GVar.adTimeStamp{
            /*
             check if timestamp difference is equal and greater than 30 minutes i.e 1800 seconds
             */
            let duration = DateFormatterLib.dateDifferenceINT(date1: timeStamp, date2: Date())
            print(duration)

            if duration <= 1800{
                // dont show ads navigate to webview
                navigateToGamesWebView()
            }else{
                //show ads & reset timestamp to current time
                K.GVar.adTimeStamp = Date()
                
                guard let interstitial = interstitial else {
                    // if ad doesnt loads make sure to make adtimestamp nil, and let user navigate to games
                    K.GVar.adTimeStamp = nil
                    navigateToGamesWebView()
                    return print("Ad wasn't ready.")
                }

                // The UIViewController parameter is an optional.
                interstitial.present(fromRootViewController: nil)
            }
        }else{
            /* assing date if it is nil and play the ad.
                also it means its the first time show the interstial ad.
             */
            K.GVar.adTimeStamp = Date()
            
            guard let interstitial = interstitial else {
                // if ad doesnt loads make sure to make adtimestamp nil, and let user navigate to games
                K.GVar.adTimeStamp = nil
                navigateToGamesWebView()
                return print("Ad wasn't ready.")
            }

            // The UIViewController parameter is an optional.
            interstitial.present(fromRootViewController: nil)
            return
        }
        
    }
    
    private func setupAds(){
        Task {
            do {
                interstitial = try await GADInterstitialAd.load(
                    withAdUnitID: K.GoogleAdIDs.gamesDetailsInterStial, request: GADRequest())
                interstitial?.fullScreenContentDelegate = self
            } catch {
                if reachability?.isReachable == true{
                    setupAds()
                }
                print("Failed to load interstitial ad with error: \(error.localizedDescription)")
            }
        }
    }
    
    private func navigateToGamesWebView(){
        let sb = UIStoryboard(name: K.StoryBoard.Games, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Games.gamesWebViewVC) as! GamesWebViewVC
        vcPush.url = self.gameData?.gameURL
        vcPush.postID = gameData?.id
        vcPush.orientation = self.gameData?.screenOrientation
        vcPush.modalTransitionStyle = .crossDissolve
        vcPush.modalPresentationStyle = .overFullScreen
        self.present(vcPush, animated: true)
    }

    @IBAction func closeBtnTapped(_ sender: UIButton) {
        if let postID = gameData?.id{
            PersistentStorage.shared.addGamesCount(postID: postID)
        }
        if let reloadType{
            if btnTapped != nil {
                btnTapped?(reloadType)
            }
        }
        self.dismiss(animated: true)
    }
}

extension GamesDetailVC : GADFullScreenContentDelegate{
    /// Tells the delegate that the ad failed to present full screen content.
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
      print("Ad did fail to present full screen content.")
    }

    /// Tells the delegate that the ad will present full screen content.
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("Ad will present full screen content.")
    }

    /// Tells the delegate that the ad dismissed full screen content.
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        print("Ad did dismiss full screen content.")
        self.navigateToGamesWebView()
        //setup ads again and wait for the timestamp 30 minutes
        self.setupAds()
    }
}
