import DocumentDetector

public struct DocumentDetectorFlowDeserializer: Decodable {
    private let documentDetectorFlow: [DocumentDetectorStep]
    
    private enum CodingKeys: String, CodingKey {
        case documentSteps
    }
    
    private struct DocumentDetectorStepStruct: Decodable {
        let document: Int?
        let stepLabel: String?
        let showStepLabel: Bool?
        let illustration: String?
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        if let documentSteps = try container.decodeIfPresent([DocumentDetectorStepStruct].self, forKey: .documentSteps) {
            let allDocuments = CafDocument.allDocuments()
            self.documentDetectorFlow = documentSteps.compactMap { step in
                guard let stepDocumentIndex = step.document,
                      let formatDocument = allDocuments[safe: stepDocumentIndex] else {
                    return nil
                }
                
                var illustration: UIImage? = nil
                
                if let illustrationUrlString = step.illustration,
                   let illustrationUrl = URL(string: illustrationUrlString),
                   let illustrationData = try? Data(contentsOf: illustrationUrl) {
                    illustration = UIImage(data: illustrationData)
                }
                
                return DocumentDetectorStep(
                    document: formatDocument,
                    stepLabel: step.stepLabel,
                    illustration: illustration,
                    showStepLabel: step.showStepLabel ?? true
                )
            }
        } else {
            self.documentDetectorFlow = []
        }
    }
    
    var getDocumentDetectorFlow: [DocumentDetectorStep] {
        documentDetectorFlow
    }
}
