//
//  FontsToolHelper.swift
//
//
//  Created by Thibaut Schmitt on 13/12/2021.
//

import Foundation
import ToolCore

enum FontsToolHelper {

    static func getFontPostScriptName(for fonts: [String], inputFolder: String) -> [FontName] {
        let fontsFilenames = Self.getFontsFilenames(fromInputFolder: inputFolder)
            .filter { fontNameWithPath in
                let fontName = URL(fileURLWithPath: fontNameWithPath)
                    .deletingPathExtension()
                    .lastPathComponent

                if fonts.contains(fontName) {
                    return true
                }
                return false
            }

        let fontsFilesnamesWithPath = fontsFilenames.map {
            "\(inputFolder)/\($0)"
        }

        return fontsFilesnamesWithPath.compactMap {
            Self.getFontName(atPath: $0)
        }
    }

    // MARK: - Private

    private static func getFontsFilenames(fromInputFolder inputFolder: String) -> [String] {
        // Get a enumerator for all files
        let fileManager = FileManager()
        guard fileManager.fileExists(atPath: inputFolder) else {
            let error = FontsToolError.inputFolderNotFound(inputFolder)
            print(error.description)
            Fonts.exit(withError: error)
        }

        let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: inputFolder)! // swiftlint:disable:this force_unwrapping

        // Filters font files
        let fontsFileNames: [String] = (enumerator.allObjects as! [String]) // swiftlint:disable:this force_cast
            .filter {
                if $0.hasSuffix(".ttf") || $0.hasSuffix(".otf") {
                    return true
                }
                return false
            }

        return fontsFileNames
    }

    private static func getFontName(atPath path: String) -> FontName {
        // print("fc-scan --format %{postscriptname} \(path)")
        // Get real font name
        let task = Shell.shell(["fc-scan", "--format", "%{postscriptname}", path])

        guard let postscriptName = task.output, task.terminationStatus == 0 else {
            let error = FontsToolError.fcScan(path, task.terminationStatus, task.output)
            print(error.description)
            Fonts.exit(withError: error)
        }

        let pathURL = URL(fileURLWithPath: path)
        let filename = pathURL
            .deletingPathExtension()
            .lastPathComponent

        return FontName(
            postscriptName: postscriptName,
            filename: filename,
            fileExtension: pathURL.pathExtension
        )
    }
}
