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

import Foundation
import ToolCore

class 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 {
                    Shell.shell(launchPath: "/usr/libexec/PlistBuddy",
                                ["-c", "add :UIAppFonts: string \($0)", infoPlist])
                }
        }

        var plistData = "<key>UIAppFonts</key>\n\t<array>\n"
        fontsToAddToPlist
            .forEach {
                plistData += "\t\t<string>\($0)</string>\n"
            }
        plistData += "\t</array>"
        
        return plistData
    }
}
