//
//  InstructionViewModel.swift
//  LMS
//
//  Created by Suraj Kumar Mandal on 10/10/23.
//

import Foundation
import Alamofire

class InstructionViewModel {
    
    var quizTime: Int?
    
    func getQuizTime(assessmentId:Int, completion: @escaping () -> Void) {
        // Perform the API request in the background thread
        DispatchQueue.global().async {
            // Make your API call here
            // You can use URLSession or any networking library of your choice
            let accessToken = UserDefaults.standard.value(forKey: "accessToken") as! String
            
            let url = ApiURL.GetQuizTime + "/\(assessmentId)"
            print(url)
            
            let headers: HTTPHeaders = [
                "Authorization": "Bearer \(accessToken)",
                "Accept": "application/json",
                "Content-Type": "application/json"
            ]
            print(headers)
            
            AF.request(url,
                       method: .get,
                       encoding: URLEncoding.httpBody,
                       headers: headers)
            .responseString { response in
                switch response.result {
                case .success(_):
                    guard let jsonData = response.data else {
                        return
                    }
                    print(jsonData)
                    guard let text = String(data: jsonData, encoding: .utf8) else {
                        print("data is not in UTF-8")
                        return
                    }
                    guard let value = Int(text) else {
                        print("text cannot be converted to Int")
                        return
                    }
                    print(value)
                    // Once you receive the data from the API
                    // Parse the data and store it in responseData
                    self.quizTime = value
                    // Call the completion handler on the main thread to update the UI
                    DispatchQueue.main.async {
                        completion()
                    }
                    break
                case .failure(let error):
                    print(error.localizedDescription)
                    //delegate.showError(error: error.localizedDescription)
                    break
                }
            }
        }
    }
    
}