//
//  ColorFileParser.swift
//  
//
//  Created by Thibaut Schmitt on 29/08/2022.
//

import Foundation

enum ColorFileParser {

    static func parse(_ inputFile: String, colorStyle: ColorStyle) -> [ParsedColor] {
        // Get content of input file
        let inputFileContent = try! String(contentsOfFile: inputFile, encoding: .utf8) // swiftlint:disable:this force_try
        let colorsByLines = inputFileContent.components(separatedBy: CharacterSet.newlines)

        // Iterate on each line of input file
        return parseLines(lines: colorsByLines, colorStyle: colorStyle)
    }

    static func parseLines(lines: [String], colorStyle: ColorStyle) -> [ParsedColor] {
        lines
            .enumerated()
            .compactMap { _, colorLine in // swiftlint:disable:this unused_enumerated
                                          // Required format:
                                          // colorName = "#RGB/#ARGB", colorName "#RGB/#ARGB", colorName "#RGB/#ARGB" "#RGB/#ARGB"
                let colorLineCleanedUp = colorLine
                    .removeLeadingWhitespace()
                    .removeTrailingWhitespace()
                    .replacingOccurrences(of: "=", with: "") // Keep compat with current file format

                guard colorLineCleanedUp.hasPrefix("#") == false, colorLineCleanedUp.isEmpty == false else {
                    // debugPrint("[\(Colors.toolName)] ⚠️  BadFormat or empty line (line number: \(lineNumber + 1)). Skip this line")
                    return nil
                }

                let colorContent = colorLineCleanedUp.split(separator: " ")

                guard colorContent.count >= 2 else {
                    let error = ColorsToolError.badFormat(colorLine)
                    print(error.description)
                    Colors.exit(withError: error)
                }

                switch colorStyle {
                case .light:
                    return ParsedColor(name: String(colorContent[0]), light: String(colorContent[1]), dark: String(colorContent[1]))

                case .all:
                    if colorContent.count == 3 {
                        return ParsedColor(name: String(colorContent[0]), light: String(colorContent[1]), dark: String(colorContent[2]))
                    }
                    return ParsedColor(name: String(colorContent[0]), light: String(colorContent[1]), dark: String(colorContent[1]))
                }
            }
    }
}
