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

import UIKit
import WebKit
import GoogleMobileAds

class GamesWebViewVC: UIViewController, WKNavigationDelegate,UIGestureRecognizerDelegate {

    var url : String?
    var orientation : ScreenOrientation?
    var count = 0
    var postID : Int?
    
    @IBOutlet weak var clickView: UIView!
    
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var adView: UIView!
    
    var startTimeStamp = Date()
    
    typealias btnTappedBlock = () -> Void
    var btnTapped : btnTappedBlock?
    var bottomBannerView = GADBannerView()

    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self,name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.removeObserver(self,name: UIApplication.willEnterForegroundNotification, object: nil)
        
        if let postID = self.postID{
            PersistentStorage.shared.addGamesCount(postID: postID,count: count)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        if let orientation, orientation == .landscape{
            DispatchQueue.main.async { [weak self] in
                guard let self else{return}
                appDelegate.deviceOrientation = .landscapeRight
                let value = UIInterfaceOrientation.landscapeRight.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
            }
        }else{
            showAds()
        }
        
        guard let url else{return}
        
        let authUrl = url + "?tk=" + AuthFunc.shareInstance.getAccessToken()
        
        let link = URL(string: authUrl)!
        let request = URLRequest(url: link)
        webView.load(request)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(didTapMethod))
        tap.numberOfTapsRequired = 1
        tap.delegate = self
        
        // Add the gesture recognizer to the web view
        clickView.addGestureRecognizer(tap)
        
        // Add observers
        NotificationCenter.default.addObserver(self,selector: #selector(appDidEnterBackground),name: UIApplication.didEnterBackgroundNotification,object: nil)
        NotificationCenter.default.addObserver(self,selector: #selector(appWillEnterForeground),name: UIApplication.willEnterForegroundNotification,object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        setNeedsStatusBarAppearanceUpdate()
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    @objc func didTapMethod(){
        count += 1
        print(count)
    }
    
    @IBAction func backBtnTapped(_ sender: UIButton) {
        PersistentStorage.shared.addOthersCount()
        
        let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.yesNoAlertVC) as! YesNoAlertVC
        vcPush.mainTitleText = "Warning"
        vcPush.contentLabel = "Clicking \"OK\" will exit you from the game. Are you sure you want to proceed?"
        vcPush.yesBtnText = "OK"
        vcPush.noBtnText = "Cancel"
        vcPush.onDoneBlock = { [weak self] mode in
            guard let self else{return}
            switch mode{
            case .yes:
                // update continue watching
                self.updateGamesView()
                if orientation == .landscape{
                    appDelegate.deviceOrientation = .portrait
                    let value = UIInterfaceOrientation.portrait.rawValue
                    UIDevice.current.setValue(value, forKey: "orientation")
                }else{
                    Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { _ in
                        self.dismiss(animated: true)
                    }
                }
            case .no:
                if let postID = self.postID{
                    PersistentStorage.shared.addGamesCount(postID: postID)
                }
                print("no")
            }
        }
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        self.present(vcPush, animated: true)
    }
    
    // MARK: - SetupAds
    
    private func showAds(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {[weak self] in
            guard let self else{return}
            AdReusable.sharedInstance.setupBannerAd(bannerView: self.bottomBannerView, in: adView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self)
        })
    }

    
    // MARK: - App LifeCycle HAndler

    @objc func appDidEnterBackground() {
        //when app goes in background make a count
        updateGamesView()
    }
    
    @objc func appWillEnterForeground() {
        //reset the start time
        startTimeStamp = Date()
    }
    
    func updateGamesView(){
        if let postID {
            let duration = DateFormatterLib.dateDifferenceINT(date1: startTimeStamp, date2: Date())
            AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.game.rawValue, duration: duration, catID: 0) { _ in}
        }
    }
    
    // MARK: - Handle Screen Transition
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        
        coordinator.animate(alongsideTransition: nil) { _ in
            self.checkOrientation()
        }
    }

    private 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.8, repeats: false) { _ in
                self.dismiss(animated: true)
            }
        } else {
            print("Device is in landscape mode")
        }
    }
}

// MARK: - Google Ad Banner Delegate

extension GamesWebViewVC : GADBannerViewDelegate{
    
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("bannerViewDidReceiveAd")
        self.adView.isHidden = false
        bannerView.alpha = 0
        bannerView.backgroundColor = #colorLiteral(red: 0.01960784314, green: 0, blue: 0.2196078431, alpha: 1)
        UIView.animate(withDuration: 0.3, animations: {
            bannerView.alpha = 1
        })
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
        print("bannerViewDidRecordImpression")
    }
    
    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillPresentScreen")
    }
    
    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillDIsmissScreen")
    }
    
    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewDidDismissScreen")
    }
}
