<commit_before>//
//  WidgetsManagerViewController.swift
//  Pock
//
//  Created by <NAME> on 30/04/21.
//

import Cocoa
import PockKit
import TinyConstraints

class WidgetsManagerViewController: NSViewController {
	
	// MARK: Cell Identifiers
	
	private enum CellIdentifiers {
		static let widgetCell: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("widgetCellIdentifier")
	}
	
    // MARK: UI Elements
	///
	/// Common UI elements
	@IBOutlet private weak var tableView: NSTableView!
	/// Selected widget's UI elements
	@IBOutlet private weak var widgetNameLabel: NSTextField!
	@IBOutlet private weak var widgetAuthorLabel: NSTextField!
	@IBOutlet private weak var widgetVersionLabel: NSTextField!
	@IBOutlet private weak var widgetInstallButton: NSButton!
	@IBOutlet private weak var widgetUpdateButton: NSButton!
	@IBOutlet private weak var widgetUninstallButton: NSButton!
	@IBOutlet private weak var widgetUpdateStatusLabel: NSTextField!
	@IBOutlet private weak var widgetPreferencesContainer: NSView!
	@IBOutlet private weak var widgetPreferencesStatusLabel: NSTextField!
    @IBOutlet private weak var widgetPreferencesHorizontalLine: NSView!
    @IBOutlet private weak var widgetPreferencesResetButton: NSButton!
	
	@IBOutlet private weak var checkForWidgetsUpdateButton: NSButton!
	
	// MARK: Data
	
	private var widgets: [PKWidgetInfo] {
		return WidgetsLoader.installedWidgets.sorted(by: { $0.name < $1.name })
	}
	private var selectedWidget: PKWidgetInfo? {
		didSet {
			if let widget = selectedWidget {
				selectedWidgetNewVersion = Updater.newVersion(for: widget)
			} else {
				selectedWidgetNewVersion = nil
			}
			updateUIElementsForSelectedWidget()
			updatePreferencesContainerForSelectedPreferences()
		}
	}
	private var selectedPreferences: PKWidgetPreference?
	private var selectedWidgetNewVersion: Updater.WidgetVersion?
	
	/// Set of disabled widget's `bundleIdentifier` to avoid user selection
	private var disabledWidgets: Set<String> = []
	
	// MARK: Overrides
	
	override var title: String? {
		get {
			return "widgets-manager.list.title".localized
		}
		set {
			view.window?.title = newValue ?? ""
		}
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		self.tableView.register(NSNib(nibNamed: "PKWidgetCellView", bundle: .main), forIdentifier: CellIdentifiers.widgetCell)
		self.configureUIElements()
		self.selectedWidget = widgets.first
		if AppController.shared.isVisible == false {
			AppController.shared.reload(shouldFetchLatestVersions: false)
		}
		NotificationCenter.default.addObserver(self, selector: #selector(reload), name: .didLoadWidgets, object: nil)
	}
	
	override func viewWillAppear() {
		super.viewWillAppear()
		NSApp.activate(ignoringOtherApps: true)
	}
	
	override func viewWillDisappear() {
		super.viewWillDisappear()
		NSApp.deactivate()
	}
	
	private func configureUIElements() {
		checkForWidgetsUpdateButton.title = "general.action.check-for-updates".localized
		widgetInstallButton.title = "menu.widgets.install-widget".localized
	}
	
	deinit {
		NotificationCenter.default.removeObserver(self)
		selectedWidget = nil
		Roger.debug("[WidgetsManager][List] - deinit")
	}
	
}

// MARK: Methods

extension WidgetsManagerViewController {
	
	@objc private func reload() {
		async { [weak self] in
			self?.tableView.reloadData()
		}
	}
	
	private func updatePreferredContentSize() {
		let frame = widgetPreferencesContainer.convert(widgetPreferencesContainer.visibleRect, to: view)
		self.preferredContentSize = NSSize(
			width: frame.origin.x + frame.size.width,
			height: frame.origin.y + frame.size.height
		)
		self.view.layout()
	}
	
	private func updateUIElementsForSelectedWidget() {
		guard let widget = selectedWidget else {
			widgetNameLabel.stringValue = "widgets-manager.list.select-widget".localized
			widgetAuthorLabel.stringValue = "--"
			widgetVersionLabel.stringValue = "--"
			widgetUninstallButton.isEnabled = false
			widgetUpdateButton.isEnabled = false
			widgetUpdateButton.isHighlighted = false
			widgetUpdateStatusLabel.isHidden = true
			return
		}
		widgetNameLabel.stringValue = widget.name
		widgetAuthorLabel.stringValue = widget.author
		widgetVersionLabel.stringValue = widget.fullVersion
		widgetUninstallButton.isEnabled = true
		widgetUpdateButton.isEnabled = selectedWidgetNewVersion?.version != nil
		widgetUpdateButton.isHighlighted = widgetUpdateButton.isEnabled
		widgetUpdateStatusLabel.isHidden = selectedWidgetNewVersion?.error == nil
		widgetUpdateStatusLabel.stringValue = selectedWidgetNewVersion?.error?.description ?? "error.unknown".localized<commit_msg>prog: keep selected widget after checking updates<commit_after>//
//  WidgetsManagerViewController.swift
//  Pock
//
//  Created by <NAME> on 30/04/21.
//

import Cocoa
import PockKit
import TinyConstraints

class WidgetsManagerViewController: NSViewController {
	
	// MARK: Cell Identifiers
	
	private enum CellIdentifiers {
		static let widgetCell: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("widgetCellIdentifier")
	}
	
    // MARK: UI Elements
	///
	/// Common UI elements
	@IBOutlet private weak var tableView: NSTableView!
	/// Selected widget's UI elements
	@IBOutlet private weak var widgetNameLabel: NSTextField!
	@IBOutlet private weak var widgetAuthorLabel: NSTextField!
	@IBOutlet private weak var widgetVersionLabel: NSTextField!
	@IBOutlet private weak var widgetInstallButton: NSButton!
	@IBOutlet private weak var widgetUpdateButton: NSButton!
	@IBOutlet private weak var widgetUninstallButton: NSButton!
	@IBOutlet private weak var widgetUpdateStatusLabel: NSTextField!
	@IBOutlet private weak var widgetPreferencesContainer: NSView!
	@IBOutlet private weak var widgetPreferencesStatusLabel: NSTextField!
    @IBOutlet private weak var widgetPreferencesHorizontalLine: NSView!
    @IBOutlet private weak var widgetPreferencesResetButton: NSButton!
	
	@IBOutlet private weak var checkForWidgetsUpdateButton: NSButton!
	
	// MARK: Data
	
	private var widgets: [PKWidgetInfo] {
		return WidgetsLoader.installedWidgets.sorted(by: { $0.name < $1.name })
	}
	private var selectedWidget: PKWidgetInfo? {
		didSet {
			if let widget = selectedWidget {
				selectedWidgetNewVersion = Updater.newVersion(for: widget)
			} else {
				selectedWidgetNewVersion = nil
			}
			updateUIElementsForSelectedWidget()
			updatePreferencesContainerForSelectedPreferences()
		}
	}
	private var selectedPreferences: PKWidgetPreference?
	private var selectedWidgetNewVersion: Updater.WidgetVersion?
	
	/// Set of disabled widget's `bundleIdentifier` to avoid user selection
	private var disabledWidgets: Set<String> = []
	
	// MARK: Overrides
	
	override var title: String? {
		get {
			return "widgets-manager.list.title".localized
		}
		set {
			view.window?.title = newValue ?? ""
		}
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		self.tableView.register(NSNib(nibNamed: "PKWidgetCellView", bundle: .main), forIdentifier: CellIdentifiers.widgetCell)
		self.configureUIElements()
		self.selectedWidget = widgets.first
		if AppController.shared.isVisible == false {
			AppController.shared.reload(shouldFetchLatestVersions: false)
		}
		NotificationCenter.default.addObserver(self, selector: #selector(reload), name: .didLoadWidgets, object: nil)
	}
	
	override func viewWillAppear() {
		super.viewWillAppear()
		NSApp.activate(ignoringOtherApps: true)
	}
	
	override func viewWillDisappear() {
		super.viewWillDisappear()
		NSApp.deactivate()
	}
	
	private func configureUIElements() {
		checkForWidgetsUpdateButton.title = "general.action.check-for-updates".localized
		widgetInstallButton.title = "menu.widgets.install-widget".localized
	}
	
	deinit {
		NotificationCenter.default.removeObserver(self)
		selectedWidget = nil
		Roger.debug("[WidgetsManager][List] - deinit")
	}
	
}

// MARK: Methods

extension WidgetsManagerViewController {
	
	@objc private func reload() {
		async { [weak self] in
            if let selectedIndex = self?.tableView.selectedRowIndexes {
                self?.tableView.reloadData()
                self?.tableView.selectRowIndexes(selectedIndex, byExtendingSelection: false)
            } else {
                self?.tableView.reloadData()
            }
		}
	}
	
	private func updatePreferredContentSize() {
		let frame = widgetPreferencesContainer.convert(widgetPreferencesContainer.visibleRect, to: view)
		self.preferredContentSize = NSSize(
			width: frame.origin.x + frame.size.width,
			height: frame.origin.y + frame.size.height
		)
		self.view.layout()
	}
	
	private func updateUIElementsForSelectedWidget() {
		guard let widget = selectedWidget else {
			widgetNameLabel.stringValue = "widgets-manager.list.select-widget".localized
			widgetAuthorLabel.stringValue = "--"
			widgetVersionLabel.stringValue = "--"
			widgetUninstallButton.isEnabled = false
			widgetUpdateButton.isEnabled = false
			widgetUpdateButton.isHighlighted = false
			widgetUpdateStatusLabel.isHidden = true
			return
		}
		widgetNameLabel.stringValue = widget.name
		widgetAuthorLabel.stringValue = widget.author
		widgetVersionLabel.stringValue = widget.fullVersion
		widgetUninstallButton.isEnabled = true
		widgetUpdateButton.isEnabled = selectedWidgetNewVersion?.version != nil
		widgetUpdateButton.isHighlighted = widgetUpdateButton.isEnabled
		widgetUpdateStatusLabel.isHidden = selectedWidgetNewVersion?.error == nil
		widgetUpdateStatusLabel.stringValue = selectedWidgetNewVersion?.error?.description ?? "error.unknown".localized
{'fraction_non_alphanumeric': 0.08765822784810126, 'fraction_numerical': 0.0016877637130801688, 'mean_word_length': 4.746060606060606, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3528060', 'n_tokens_mistral': 2965, 'n_tokens_neox': 2684, 'n_words': 604}