//
//  Generate.swift
//  
//
//  Created by Thibaut Schmitt on 30/08/2022.
//

import ArgumentParser
import Foundation
import ToolCore

struct Generate: ParsableCommand {

    // MARK: - CommandConfiguration

    static var configuration = CommandConfiguration(
        abstract: "A utility to generate ressources based on a configuration file",
        version: ResgenSwiftVersion
    )

    // MARK: - Static

    static let toolName = "Generate"

    // MARK: - Command Options

    @OptionGroup var options: GenerateOptions

    // MARK: - Run

    func run() throws {
        print("[\(Self.toolName)] Starting Resgen with configuration: \(options.configurationFile)")

        // Parse
        let configuration = ConfigurationFileParser.parse(options.configurationFile)
        print("Found configurations :")
        print("  - \(configuration.analytics.count) analytics configuration(s)")
        print("  - \(configuration.colors.count) colors configuration(s)")
        print("  - \(configuration.fonts.count) fonts configuration(s)")
        print("  - \(configuration.images.count) images configuration(s)")
        print("  - \(configuration.strings.count) strings configuration(s)")
        print("  - \(configuration.tags.count) tags configuration(s)")
        print()

        if let architecture = configuration.architecture {
            ArchitectureGenerator.writeArchitecture(
                architecture,
                projectDirectory: options.projectDirectory
            )
        }

        // Execute commands
        configuration.runnableConfigurations
            .forEach {
                let begin = Date()
                $0.run(
                    projectDirectory: options.projectDirectory,
                    force: options.forceGeneration
                )
                print("Took: \(Date().timeIntervalSince(begin))s\n")
            }

        print("[\(Self.toolName)] Resgen ended")
    }
}
