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

import Foundation
import ToolCore

enum FontPlistGenerator {

    static func generatePlistUIAppsFontContent(for fonts: [FontName], infoPlistPaths: [String]) -> String {
        let fontsToAddToPlist = fonts
            .compactMap { $0 }

        // Update each plist
        infoPlistPaths.forEach { infoPlist in
            // Remove UIAppFonts value
            Shell.shell(
                launchPath: "/usr/libexec/PlistBuddy",
                ["-c", "delete :UIAppFonts", infoPlist]
            )

            // Add UIAppFonts empty array
            debugPrint("Will PlistBuddy -c add :UIAppFonts array \(infoPlist)")
            Shell.shell(
                launchPath: "/usr/libexec/PlistBuddy",
                ["-c", "add :UIAppFonts array", infoPlist]
            )

            // Fill array with fonts
            fontsToAddToPlist
                .forEach { fontName in
                    Shell.shell(
                        launchPath: "/usr/libexec/PlistBuddy",
                        ["-c", "add :UIAppFonts: string \(fontName.filename).\(fontName.fileExtension)", infoPlist]
                    )
                }
        }

        var plistData = "<key>UIAppFonts</key>\n\t<array>\n"
        fontsToAddToPlist
            .forEach { fontName in
                plistData += "\t\t<string>\(fontName.filename).\(fontName.fileExtension)</string>\n"
            }
        plistData += "\t</array>"

        return plistData
    }
}
