//
//  ColorExtensionGenerator.swift
//  
//
//  Created by Thibaut Schmitt on 20/12/2021.
//

import Foundation
import ToolCore

struct ColorExtensionGenerator {
    
    let colors: [ParsedColor]
    let extensionClassname: String
    
    // MARK: - UIKit
    
    static func writeExtensionFile(colors: [ParsedColor],
                                   staticVar: Bool,
                                   extensionName: String,
                                   extensionFilePath: String,
                                   isSwiftUI: Bool) {
        // Create extension content
        let extensionContent = Self.getExtensionContent(colors: colors,
                                                        staticVar: staticVar,
                                                        extensionName: extensionName,
                                                        isSwiftUI: isSwiftUI)
        
        // Write content
        let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
        do {
            try extensionContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
        } catch let error {
            let error = ColorsToolError.writeExtension(extensionFilePath, error.localizedDescription)
            print(error.description)
            Colors.exit(withError: error)
        }
    }
    
    static func getExtensionContent(colors: [ParsedColor],
                                    staticVar: Bool,
                                    extensionName: String,
                                    isSwiftUI: Bool) -> String {
        [
            Self.getHeader(extensionClassname: extensionName, isSwiftUI: isSwiftUI),
            Self.getProperties(for: colors, withStaticVar: staticVar, isSwiftUI: isSwiftUI),
            Self.getFooter()
        ]
            .joined(separator: "\n")
    }
    
    private static func getHeader(extensionClassname: String, isSwiftUI: Bool) -> String {
        """
        // Generated by ResgenSwift.\(Colors.toolName) \(ResgenSwiftVersion)

        import \(isSwiftUI ? "SwiftUI" : "UIKit")

        extension \(extensionClassname) {\n
        """
    }
    
    private static func getFooter() -> String {
        """
        }
        
        """
    }
    
    private static func getProperties(for colors: [ParsedColor],
                                      withStaticVar staticVar: Bool,
                                      isSwiftUI: Bool) -> String {
        colors.map {
            $0.getColorProperty(isStatic: staticVar, isSwiftUI: isSwiftUI)
        }
        .joined(separator: "\n\n")
    }
}
