 [-s|--set|set displayIndex width scale] [-r|--set-retina|retina displayIndex width],
 
 Here are some examples:
-   -h               get help
-   -l               list displays
-   -m 0             list all mode from a certain display
-   -m               shorthand for -m 0
-   -s 0 800 600 1   set resolution of display 0 to 800 x 600 @ 1x [@ 60Hz]
-   -s 0 800 600     set resolution of display 0 to 800 x 600 @(highest scale factor)
-   -s 0 800 1       set resolution of display 0 to 800 [x 600] @ 1x [@ 60Hz]
-   -s 0 800         shorthand for -s 0 800 2 (highest scale factor)
-   -s 800           shorthand for -s 0 800 2 (highest scale factor)
-   -r 0 800         shorthand for -s 0 800 2
-   -r 800           shorthand for -s 0 800 2
-   -d               toggle macOS Dark Mode
-   -sl              sleep display
+ -h               get help
+ -l               list displays
+ -m 0             list all mode from a certain display
+ -m               shorthand for -m 0
+ -s 0 800 600 1   set resolution of display 0 to 800 x 600 @ 1x [@ 60Hz]
+ -s 0 800 600     set resolution of display 0 to 800 x 600 @(highest scale factor)
+ -s 0 800 1       set resolution of display 0 to 800 [x 600] @ 1x [@ 60Hz]
+ -s 0 800         shorthand for -s 0 800 2 (highest scale factor)
+ -s 800           shorthand for -s 0 800 2 (highest scale factor)
+ -r 0 800         shorthand for -s 0 800 2
+ -r 800           shorthand for -s 0 800 2
+ -d               toggle macOS Dark Mode
+ -sl              sleep display
 """)
 }
 
 func main() {
-    let screens = Screens()
-
-    let arguments = CommandLine.arguments
-    let count = arguments.count
-    guard count >= 2 else {
-        seeHelp()
-        return
-    }
-    switch arguments[1] {
-    case "-l", "--list", "list":
-        screens.listDisplays()
-    case "-m", "--mode", "mode":
-        var displayIndex = 0
-        if count > 2, let index = Int(arguments[2]) {
-            displayIndex = index
-        }
-        if displayIndex < screens.displayCount {
-            print("Supported Modes for Display \(displayIndex):")
-            screens.listModes(displayIndex)
-        } else {
-            print("Display index not found. List all available displays by:\n    screen-resolution-switcher -l")
-        }
-    case "-s", "--set", "set", "-r", "--set-retina", "retina":
-        screens.set(with:DisplayUserSetting( arguments ))
-    case "-d", "--toggle-dark-mode":
-        DarkMode().toggle()
-    case "-sl", "--sleep", "sleep":
-        sleepDisplay()
-    default:
-        seeHelp()
-    }
+  let screens = Screens()
+
+  let arguments = CommandLine.arguments
+  let count = arguments.count
+  guard count >= 2 else {
+      seeHelp()
+      return
+  }
+  switch arguments[1] {
+  case "-l", "--list", "list":
+      screens.listDisplays()
+  case "-m", "--mode", "mode":
+      var displayIndex = 0
+      if count > 2, let index = Int(arguments[2]) {
+          displayIndex = index
+      }
+      if displayIndex < screens.displayCount {
+          print("Supported Modes for Display \(displayIndex):")
+          screens.listModes(displayIndex)
+      } else {
+          print("Display index not found. List all available displays by:\n    screen-resolution-switcher -l")
+      }
+  case "-s", "--set", "set", "-r", "--set-retina", "retina":
+      screens.set(with:DisplayUserSetting( arguments ))
+  case "-d", "--toggle-dark-mode":
+      DarkMode().toggle()
+  case "-sl", "--sleep", "sleep":
+      //if #available(macOS 12.0, *) {
+          sleepDisplay()
+      //}
+  default:
+      seeHelp()
+  }
 }
 
 #if os(macOS)
-    // run it
-    main()
+  // run it
+  main()
 #else
-    print("This script currently only runs on macOS")
+  print("This script currently only runs on macOS")
 #endif

// 6    id, width, scale
// 7    id, width, height, scale
struct DisplayUserSetting {
    var displayIndex = 0, width = 0
    var height, scale:Int?
    init(_ arr:[String]) {
        var args = arr.compactMap { Int($0) }
        
        if args.count < 1 { return }
        
        if args[0] > Screens.MAX_DISPLAYS { args.insert(0 /* displayIndex */, at:0) }

        if args.count < 2 { return }

        displayIndex = args[0]
        width = args[1]

        if args.count == 2 { return }

        if args[2] > DisplayInfo.MAX_SCALE {
            height = args[2]
            if args.count > 3 { scale = args[3] }
        }
        else {
            scale = args[2]
            if args.count > 3 { height = args[3] }
        }
    }

    // override a lesser-used operator to simplify display mode checks
    static func == (lhs: Self, rhs: DisplayInfo) -> Bool {
        return rhs == lhs
    }
}

class Screens {
    // assume at most 8 display connected
    static let MAX_DISPLAYS = 8
    var maxDisplays = MAX_DISPLAYS
    // actual number of display
    var displayCount:Int = 0
    var dm = [DisplayManager]()
    
    init() {
        // actual number of display
        var displayCount32:UInt32 = 0
        var displayIDs = [CGDirectDisplayID](repeating: 0, count:maxDisplays)

        guard CGGetOnlineDisplayList(UInt32(maxDisplays), &displayIDs, &displayCount32) == .success else {
            print("Error on getting online display List.")
            return
        }
        displayCount = Int( displayCount32 )
        dm = displayIDs
            .filter { $0 != 0 }
            .map { DisplayManager($0) }
    }

    // print a list of all displays
    // used by -l
    func listDisplays() {
        for (i, m) in dm.enumerated() {
           m.printForOneDisplay("Display \(i):")
        }
    }

    func listModes(_ displayIndex:Int) {
        dm[displayIndex].printFormatForAllModes()
    }

    func set(with setting:DisplayUserSetting) {
        dm[setting.displayIndex].set(with:setting)
    }
}

// darkMode toggle code with JXA ;-)
// Method from Stackoverflow User: bacongravy
// https://stackoverflow.com/questions/44209057
struct DarkMode {
    static let scriptString = """
    pref = Application(\"System Events\").appearancePreferences
    pref.darkMode = !pref.darkMode()
"""
    let script = OSAScript.init(source: scriptString, language: OSALanguage.init(forName: "JavaScript"))
    
    init() {
        var compileError: NSDictionary?

        script.compileAndReturnError(&compileError)
    }
    func toggle() {
        var scriptError: NSDictionary?

        if let result = script.executeAndReturnError(&scriptError)?.stringValue { print("Dark Mode:", result) }
    }
}

func sleepDisplay() {
    let r = IORegistryEntryFromPath(kIOMainPortDefault, strdup("IOService:/IOResources/IODisplayWrangler"))

    IORegistryEntrySetCFProperty(r, ("IORequestIdle" as CFString), kCFBooleanTrue)
    IOObjectRelease(r)
}

func seeHelp() {

#!/usr/bin/env xcrun -sdk macosx swift
//vim: ts=2:tw=78: et:
//
//  x2.swift
//  
