//
//  SailassistApp.swift
//  Sailassist
//
//  Created by Mamoru Sugita on 2023/10/13.
//

import SwiftUI

@main
struct SailassistApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate{
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        let config = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
        config.delegateClass = SceneDelegate.self
        return config
    }
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate, ObservableObject {
    weak var windowScene: UIWindowScene?
    var tabWindow: UIWindow?
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        windowScene = scene as? UIWindowScene
    }
    
    
    func addTabBar(_ selectedTabModel: SelectedTabModel){
        guard let scene = windowScene else{
            return
        }
        
        let tabBarController = UIHostingController(rootView:
            CustomTabBar()
                .environmentObject(selectedTabModel)
                .frame(maxHeight: .infinity, alignment: .bottom)
        )
        
        tabBarController.view.backgroundColor = .clear
        
        let tabWindow = PassThroughWindow(windowScene: scene)
        tabWindow.rootViewController = tabBarController
        tabWindow.isHidden = false
        
        self.tabWindow = tabWindow
    }
}


class PassThroughWindow: UIWindow{
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let view = super.hitTest(point, with: event) else { return nil}
        return rootViewController?.view == view ? nil : view
    }
}

// MARK: コメント出力を消す
func print(debug: Any = "", function: String = #function, file: String = #file, line: Int = #line) {
    #if DEBUG
        var filename: NSString = file as NSString
        filename = filename.lastPathComponent as NSString
        // Swift.print("File: \(filename), Line: \(line), Func: \(function) \n\(debug)")

        let outstr = String( format: "APPDebug File: %@, Line: %d, Func: %@\n\(debug)", filename, line, function )
        // Swift.print( outstr ) NSLog がある時は、両方に出るのでいらない
        NSLog( outstr )     // デバッグコンソールにも出力
    #endif
}
