//
//  YHAppleLoginManager.swift
//  galaxy
//
//  Created by edy on 2024/5/29.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AuthenticationServices

class YHAppleLoginManager: NSObject {
    
    static let shared = YHAppleLoginManager()
    let viewModel = YHAppleLoginViewModel()
    // 防止苹果登录按钮反复点击
    var isAppleLoginBtnEnabled = true
    var success: (([String: Any]) ->())?
    
    func appleLogin() {
        if !isAppleLoginBtnEnabled {
            return
        }
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let vc = ASAuthorizationController(authorizationRequests: [request])
        vc.delegate = self
        vc.presentationContextProvider = self
        vc.performRequests()
        isAppleLoginBtnEnabled = false
    }
}

extension YHAppleLoginManager: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        
        isAppleLoginBtnEnabled = true
        var userId = ""
        var email = ""
        var fullName = ""
        var authorizationCodeStr = ""
        var identityTokenStr = ""
        
        let credential = authorization.credential
        if credential is ASPasswordCredential {
            let passwdCredential = credential as! ASPasswordCredential
            userId = passwdCredential.user
            let username = passwdCredential.user
            let password = passwdCredential.password
            printLog("username:\(username), passwd:\(password)")
            
        } else if credential is ASAuthorizationAppleIDCredential {
            let appleIdCredential = credential as! ASAuthorizationAppleIDCredential
            userId = appleIdCredential.user
            email = appleIdCredential.email ?? ""
            fullName = appleIdCredential.fullName?.givenName ?? ""
            let authorizationCode = appleIdCredential.authorizationCode
            authorizationCodeStr = String(decoding: authorizationCode!, as: UTF8.self)
            let identityToken = appleIdCredential.identityToken
            identityTokenStr = String(decoding: identityToken!, as: UTF8.self)
            let realUserStatus = appleIdCredential.realUserStatus
        }
        
        printLog("APPLE LOGIN userId:\(userId)")
        printLog("APPLE LOGIN identityToken:\(identityTokenStr)")
        printLog("APPLE LOGIN authorizationCode: \(authorizationCodeStr)")
        
        let params:[String: Any] = ["full_name": fullName,
                                    "user_id": userId,
                                    "email": email,
                                    "authorization_code": authorizationCodeStr,
                                    "identity_token": identityTokenStr]
                                    
        
        self.success?(params)
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        printLog("Apple login FAILED: \(error.localizedDescription)")
        isAppleLoginBtnEnabled = true
        if error is ASAuthorizationError {
            let err = error as! ASAuthorizationError
            // 在这里处理 AuthenticationError
            handleAuthenticationError(err)
        }
    }
    
    func handleAuthenticationError(_ error: ASAuthorizationError) {
        if error.code == .canceled || error.code == .unknown {
            return
        }
        YHHUD.flash(message: "苹果登录失败 原因：\(error.localizedDescription)")
    }
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return  UIApplication.shared.yhKeyWindow()!
    }
}
    
