import DocumentDetector

public struct UploadSettingsDeserializer: Decodable {
    private var uploadSettings: DDUploadSettings?
    
    private enum CodingKeys: String, CodingKey {
        case uploadSettings
    }
    
    private struct UploadSettingsStruct: Decodable {
        let enable: Bool?
        let compress: Bool?
        let fileFormats: [Int]?
        let maxFileSize: Int?
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        let uploadSettingsContainer = try container.decodeIfPresent(UploadSettingsStruct.self, forKey: .uploadSettings)
                
        uploadSettings = try createUploadSettings(container: uploadSettingsContainer)
    }
    
    var getUploadSettings: DDUploadSettings? {
        uploadSettings
    }
    
    private func createUploadSettings(container: UploadSettingsStruct?) throws -> DDUploadSettings? {
        let parsedFileFormats = try parseFileFormats(fileFormats: container?.fileFormats) ?? [.png, .jpeg, .pdf]
        let fileSizeInBytes = ((container?.maxFileSize ?? 10000) * 1000) // Convertion to bytes
        
        return DDUploadSettings(
            enable: container?.enable ?? false,
            compress: container?.compress ?? true,
            fileFormats: parsedFileFormats,
            maximumFileSize: fileSizeInBytes
        )
    }
    
    private func parseFileFormats(fileFormats: [Int]?) throws -> [CafFileFormat]? {
        guard let fileFormatsArray = fileFormats else {
            return nil
        }
        var fileFormats = [CafFileFormat]()
        for file in fileFormatsArray {
            if let fileFormatString = fileFormatString(forIntValue: file),
               let fileFormat = CafFileFormat(rawValue: fileFormatString) {
                fileFormats.append(fileFormat)
            }
        }
        return fileFormats.isEmpty ? nil : fileFormats
    }
    
    private func fileFormatString(forIntValue intValue: Int) -> String? {
        switch intValue {
        case 0:
            return CafFileFormat.png.rawValue
        case 2:
            return CafFileFormat.jpeg.rawValue
        case 3:
            return CafFileFormat.pdf.rawValue
        default:
            return nil
        }
    }
}
