//
//  Tag.swift
//
//
//  Created by Thibaut Schmitt on 10/01/2022.
//

import ArgumentParser
import Foundation
import ToolCore

struct Tags: ParsableCommand {

    // MARK: - Command Configuration

    static let configuration = CommandConfiguration(
        abstract: "Generate tags extension file.",
        version: ResgenSwiftVersion
    )

    // MARK: - Static

    static let toolName = "Tags"
    static let defaultExtensionName = "Tags"
    static let noTranslationTag: String = "notranslation"

    // MARK: - Command Options

    @OptionGroup var options: TagsOptions

    // MARK: - Run

    mutating func run() {
        print("[\(Self.toolName)] Starting tags generation")
        print("[\(Self.toolName)] Will use inputFile \(options.inputFile) to generate strings for lang: \(options.lang)")

        // Check requirements
        guard checkRequirements() else { return }

        print("[\(Self.toolName)] Will generate tags")

        // Parse input file
        let sections = TwineFileParser.parse(options.inputFile)

        // Generate extension
        TagsGenerator.writeExtensionFiles(
            sections: sections,
            lang: options.lang,
            tags: ["ios", "iosonly", Self.noTranslationTag],
            isStatic: options.staticMembers,
            extensionName: options.extensionName,
            extensionFilePath: options.extensionFilePath,
            visibility: options.extensionVisibility
        )

        print("[\(Self.toolName)] Tags generated")
    }

    // MARK: - Requirements

    private func checkRequirements() -> Bool {
        let fileManager = FileManager()

        // Input file
        guard fileManager.fileExists(atPath: options.inputFile) else {
            let error = StringiumError.fileNotExists(options.inputFile)
            print(error.description)
            Stringium.exit(withError: error)
        }

        // Check if needed to regenerate
        guard GeneratorChecker.shouldGenerate(
            force: options.forceGeneration,
            inputFilePath: options.inputFile,
            extensionFilePath: options.extensionFilePath
        ) else {
            print("[\(Self.toolName)] Tags are already up to date :) ")
            return false
        }

        return true
    }
}
