//
//  AppDelegate.swift
//  FirefoxVideoStopper
//
//  Created by gltchitm on 4/11/21.
//

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var window: NSWindow!
    @IBOutlet weak var rddSelect: NSPopUpButton!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        updateRDDList()
    }

    func updateRDDList() {
        rddSelect.removeAllItems()
        for app in NSWorkspace.shared.runningApplications {
            if app.bundleIdentifier == "org.mozilla.plugincontainer" {
                if app.localizedName?.contains("RDD") == true {
                    rddSelect.addItem(
                        withTitle: "\(app.processIdentifier) - \(app.localizedName ?? "RDD")"
                    )
                }
            }
        }
    }

    func esrchWarning() {
        let alert = NSAlert()
        alert.messageText = "Operation Failed"
        alert.informativeText = "This RDD process may no longer exist. Update RDD process list?"
        alert.alertStyle = .critical
        alert.addButton(withTitle: "Yes")
        alert.addButton(withTitle: "No")
        if alert.runModal() == .alertFirstButtonReturn {
            self.updateRDDList()
        }
    }
    func signalFailedWarning() {
        let alert = NSAlert()
        alert.messageText = "Operation Failed"
        alert.informativeText = "Could not send the signal."
        alert.alertStyle = .critical
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }
    func noSelectedRDDProcessWarning() {
        let alert = NSAlert()
        alert.messageText = "Operation Failed"
        alert.informativeText = "No selected RDD process."
        alert.alertStyle = .critical
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }

    @IBAction func enableVideo(_ sender: Any) {
        if rddSelect.selectedItem == nil {
            noSelectedRDDProcessWarning()
        } else {
            let pid = Int(rddSelect.selectedItem!.title.components(separatedBy: " - ")[0])!
            if kill(pid_t(pid), SIGCONT) != 0 {
                if errno == ESRCH {
                    esrchWarning()
                } else {
                    signalFailedWarning()
                }
            }
        }
    }
    @IBAction func disableVideo(_ sender: Any) {
        if rddSelect.selectedItem == nil {
            noSelectedRDDProcessWarning()
        } else {
            let pid = Int(rddSelect.selectedItem!.title.components(separatedBy: " - ")[0])!
            if kill(pid_t(pid), SIGSTOP) != 0 {
                if errno == ESRCH {
                    esrchWarning()
                } else {
                    signalFailedWarning()
                }
            }
        }
    }
}
