//
//  AdReusable.swift
//  WOKA
//
//  Created by MacBook Pro on 16/09/24.
//

import UIKit
import GoogleMobileAds

class AdReusable {
    
    // Singleton instance
    static let sharedInstance = AdReusable()
    
    // Private init to prevent creating additional instances
    private init() {}

    // Function to set up banner ads with an existing banner view
    func setupBannerAd(bannerView: GADBannerView, in containerView: UIView, adUnitID: String, viewController: GADBannerViewDelegate & UIViewController, height: CGFloat? = 0.0, width: CGFloat? = 0.0) {
        
        // Adjust the view width and height based on provided values
        let viewWidth = containerView.frame.inset(by: containerView.safeAreaInsets).width - (width ?? 0)
        let viewHeight = containerView.frame.height - (height ?? 0)
        
        // Create the adaptive banner size
//        let adaptiveSize = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
        
        let adaptiveSize = GADPortraitInlineAdaptiveBannerAdSizeWithWidth(viewWidth)
        bannerView.adSize = adaptiveSize
        
        // Set the delegate to handle banner events
        bannerView.delegate = viewController
        
        // Adjust the banner's frame
        bannerView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
        
        // Center the banner within the containerView
        bannerView.center = CGPoint(x: containerView.frame.width / 2, y: containerView.frame.height / 2)
        
        // If height is provided, add rounded corners
        if let heightValue = height, heightValue > 0 {
            bannerView.layer.cornerRadius = 4
            bannerView.clipsToBounds = true
        }
        
        // Add the banner view to the container
        containerView.addSubview(bannerView)
        
        // Set the ad unit ID and root view controller for the banner
        bannerView.adUnitID = adUnitID
        bannerView.rootViewController = viewController
        
        // Load the ad request
        bannerView.load(GADRequest())
        
        // Ensure the layout is updated
        containerView.layoutIfNeeded()
    }
}

