import Foundation
import UIKit

/// singleton authentication class that represents authentification
class Auth {
    
    static let shared = Auth()
    
    /// set token from authentification
    /// - Parameter token: auth token
    func setToken(token: String) {
        UserDefaults.userToken = token
        let user = UserDetail(ID_Login: token)
        let userDetail = UserDetailResult(completion: { result in
            guard let user = result as? UserDetailResult else { return }
            UserDefaults.userId = user.ID
            UserDefaults.personName = user.Person
            UserDefaults.personId = user.ID_Person
        })
        API.shared.call(object: user, result: userDetail, serviceName: .userManagement)
    }
    
    /// helper function for returning unit
    func getUnit() {
        guard let token = UserDefaults.userToken,
            let id = UserDefaults.userId else { return }
        let account = UserRoleAll(ID_Login: token, ID_User: id)
        let acountDetail = UserRoleAllResult(completion: { result in
            guard let res = result as? UserRoleAllResult else { return }
            print(res)
        })
        API.shared.call(object: account, result: acountDetail, serviceName: .userManagement)
    }
    
    /// function that erases all stored data about the user and forces app to start
    func logOut() {
        guard UserDefaults.userToken != nil else { return }
        UserDefaults.userToken = nil
        UserDefaults.userId = nil
        UserDefaults.personName = nil
        UserDefaults.personId = nil
        goToStartApp()
    }
    
    /// function that forces the app to go to starting screen
    func goToStartApp() {
        DispatchQueue.main.async {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                let sceneDelegate = windowScene.delegate as? SceneDelegate else { return }
            sceneDelegate.goToStartApplication()
        }
    }
}
