//
//  closeWindows.swift
//  playbtest
//
//  Created by 忆海16 on 2024/11/11.
//

import Foundation
import UIKit

class closeWindows {
    
      @objc static func removeADVCByDelayTime(_ delayTime: Int) {
          DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayTime)) {
//              CloseAD.removeVungleFullScreenPresenter()
              closeWindows.closeADWindow()
          }
      }
      
      @objc static func closeADWindow() {
          print("Executing closeADWindow - First Pass")
          performCloseADWindowActions()
          
          print("Executing closeADWindow - Second Pass")
//          performCloseADWindowActions()
      }
      
      private static func performCloseADWindowActions() {
          guard let keyWindow = UIApplication.shared.keyWindow else { return }
          
          keyWindow.subviews.forEach { view in
              if let vc = view.subviews.first?.next as? UIViewController {
                  
                  if vc.isKind(of: NSClassFromString("ALAppLovinVideoViewController") ?? UIViewController.self) ||
                      vc.isKind(of: NSClassFromString("ALVASTVideoViewController") ?? UIViewController.self) {
                      
                      print("Removing ad view from window...")
                      view.removeFromSuperview() // Remove the ad view directly from the window’s subviews
                    
                  }
              }
              closeWindows.removeVungleFullScreenPresenter()
          }
         
      }
      
      private static func removeVungleFullScreenPresenter() {
          guard let keyWindow = UIApplication.shared.keyWindow else { return }
          if let foundView = findFullScreenPresenterInViewController(keyWindow.rootViewController) {
              print("Found FullScreenPresenter instance: \(foundView)")
              foundView.view.removeFromSuperview()
              print("FullScreenPresenter view removed from superview.")
          } else {
              print("FullScreenPresenter not found.")
          }
      }
      
      private static func findFullScreenPresenterInViewController(_ viewController: UIViewController?) -> UIViewController? {
          guard let viewController = viewController else { return nil }
          
          if viewController.isKind(of: NSClassFromString("VungleAdsSDK.FullScreenPresenter") ?? UIViewController.self) {
              return viewController
          }
          
          for childViewController in viewController.children {
              if let foundVC = findFullScreenPresenterInViewController(childViewController) {
                  return foundVC
              }
          }
          
          if let presentedVC = viewController.presentedViewController {
              return findFullScreenPresenterInViewController(presentedVC)
          }
          
          return nil
      }

}
