//
//  ImageExtensionGenerator.swift
//  
//
//  Created by Thibaut Schmitt on 14/02/2022.
//

import ToolCore
import Foundation

class ImageExtensionGenerator {
    
    // MARK: - UIKit
    
    static func generateExtensionFile(images: [ParsedImage],
                                      staticVar: Bool,
                                      inputFilename: String,
                                      extensionName: String,
                                      extensionFilePath: String,
                                      isSwiftUI: Bool) {
        // Create extension conten1t
        let extensionContent = Self.getExtensionContent(images: images,
                                                        staticVar: staticVar,
                                                        extensionName: extensionName,
                                                        inputFilename: inputFilename,
                                                        isSwiftUI: isSwiftUI)
        
        // Write content
        let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
        do {
            try extensionContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
        } catch let error {
            let error = ImagesError.writeFile(extensionFilePath, error.localizedDescription)
            print(error.description)
            Images.exit(withError: error)
        }
    }
    
    static func getExtensionContent(images: [ParsedImage],
                                    staticVar: Bool,
                                    extensionName: String,
                                    inputFilename: String,
                                    isSwiftUI: Bool) -> String {
        [
            Self.getHeader(inputFilename: inputFilename, extensionClassname: extensionName, isSwiftUI: isSwiftUI),
            Self.getProperties(images: images, staticVar: staticVar, isSwiftUI: isSwiftUI),
            Self.getFooter()
        ]
            .joined(separator: "\n")
    }
    
    private static func getHeader(inputFilename: String,
                                  extensionClassname: String,
                                  isSwiftUI: Bool) -> String {
        """
        // Generated by ResgenSwift.\(Images.toolName) \(ResgenSwiftVersion)
        // Images from \(inputFilename)
        
        import \(isSwiftUI ? "SwiftUI" : "UIKit")
        
        extension \(extensionClassname) {
        """
    }
    
    private static func getProperties(images: [ParsedImage], staticVar: Bool, isSwiftUI: Bool) -> String {
        images
            .map { "\n\($0.getImageProperty(isStatic: staticVar, isSwiftUI: isSwiftUI))" }
            .joined(separator: "\n")
    }
    
    private static func getFooter() -> String {
        """
        }
        
        """
    }
}
