//
/*
 * Copyright (c) 2022 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Foundation
import CryptoKit

@objcMembers class LoginProtectionService : NSObject {
    
    @objc func isValid(_ homeserverAddress: String, ignoreNetworkConnectionLost: Bool = false) async -> Bool {
        // bwi #6162 a homeserveraddress is valid when there is either
        // a) no homeserver protection (bwm)
        // b) tokenized protection and there is a valid token
        // c) hashed protection and there is a valid hash (this will be disabled soon)
        // d) b) && c) can be combined for now
        
        var validHomeserver = false
        
        if BWIBuildSettings.shared.bwiEnableTokenizedLoginProtection {
            
            let tokenVerificator = ServerTokenVerificator()
            
            let tokens = await tokenVerificator.fetchToken(baseURL: homeserverAddress)
            
            if tokens == nil && ignoreNetworkConnectionLost {
                validHomeserver = true
            } else {
                if let tokens = tokens, !tokens.isEmpty {
                    validHomeserver = tokenVerificator.verifyToken(baseURL: homeserverAddress, tokens: tokens)
                }
            }
        }
        
        return validHomeserver
    }
    
    private func normalizeLoginUrl(_ urlString: String) -> String {
        var tmpString = urlString.replacingOccurrences(of: "https://", with: "")
        tmpString = tmpString.replacingOccurrences(of: "http://", with: "")
        
        return tmpString
    }
}
