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

import Foundation
import ToolCore

enum ColorXcassetHelper {

    static func generateXcassetColors(colors: [ParsedColor], to xcassetsPath: String) {
        colors.forEach {
            Self.generateColorSetAssets(from: $0, to: xcassetsPath)
        }
    }

    // Generate ColorSet in XCAssets file
    private static func generateColorSetAssets(from color: ParsedColor, to xcassetsPath: String) {
        // Create ColorSet
        let colorSetPath = "\(xcassetsPath)/Colors/\(color.name).colorset"
        let contentsJsonPath = "\(colorSetPath)/Contents.json"

        let fileManager = FileManager()
        if fileManager.fileExists(atPath: colorSetPath) == false {
            do {
                try fileManager.createDirectory(
                    atPath: colorSetPath,
                    withIntermediateDirectories: true
                )
            } catch {
                let error = ColorsToolError.createAssetFolder(colorSetPath)
                print(error.description)
                Colors.exit(withError: error)
            }
        }

        // Write content in Contents.json
        let contentsJsonPathURL = URL(fileURLWithPath: contentsJsonPath)
        do {
            try color.contentsJSON().write(to: contentsJsonPathURL, atomically: false, encoding: .utf8)
        } catch {
            let error = ColorsToolError.writeAsset(error.localizedDescription)
            print(error.description)
            Colors.exit(withError: error)
        }
    }
}
