import Foundation

enum LaunchAgent {
    static let label = "com.pommedoro.app"
    static let plistName = "\(label).plist"

    static var plistURL: URL {
        let home = FileManager.default.homeDirectoryForCurrentUser
        return home.appendingPathComponent("Library/LaunchAgents/\(plistName)")
    }

    static var appPath: String {
        return "/Applications/Pommedoro.app/Contents/MacOS/Pommedoro"
    }

    static func isInstalled() -> Bool {
        return FileManager.default.fileExists(atPath: plistURL.path)
    }

    static func install() {
        let plist: [String: Any] = [
            "Label": label,
            "Program": appPath,
            "RunAtLoad": true,
            "KeepAlive": false
        ]

        let launchAgentsDir = plistURL.deletingLastPathComponent()
        try? FileManager.default.createDirectory(at: launchAgentsDir, withIntermediateDirectories: true)

        let data = try? PropertyListSerialization.data(
            fromPropertyList: plist,
            format: .xml,
            options: 0
        )

        if let data = data {
            try? data.write(to: plistURL)
            NSLog("Pommedoro: LaunchAgent installed at \(plistURL.path)")
        }
    }

    static func uninstall() {
        try? FileManager.default.removeItem(at: plistURL)
        NSLog("Pommedoro: LaunchAgent removed")
    }
}
