//
//  ServerManagerExtras.swift
//  Postgres
//
//  Created by Jakob Egger on 22.12.22.
//  Copyright © 2022 postgresapp. All rights reserved.
//

import Foundation


// This extension to the ServerManager is available only in the main app
// It is not available in the login helper or in the menu helper
extension ServerManager {
	func createDefaultServer() {
		let latestBinary = BinaryManager.shared.getLatestBinary()
		
		// It is possible to build Postgres.app without a latest stable version
		// (mostly useful during development)
		// In that case we don't add a server
		guard let latestBinary else { return }
		
		// check if we already autogenerated a server with the latest version
		// we don't want to autogenerate the server if it was manually deleted,
		// unless there are no servers at all
		var autocreatedVersions = UserDefaults.shared.stringArray(forKey: "AutoCreatedServerVersions") ?? []
		if autocreatedVersions.contains(latestBinary.version) && servers.count != 0 {
			return
		}
		
		// check if there already is a server with the latest version
		// this should usually not happen, but we have it just in case eg. user deletes user defaults
		for server in servers {
			if server.binPath == latestBinary.binPath {
				return
			}
		}
		
		// check if there already is a server with the same var path (eg. just with a different binary path)
		let varPath = FileManager().applicationSupportDirectoryPath().appendingFormat("/var-%@", latestBinary.version)
		for server in servers {
			if server.varPath == varPath {
				return
			}
		}

		// autogenerate a server with the latest version
		// put it in the first spot (top of the list) so it gets selected automatically
		let newDefaultServer = Server(
			name: "PostgreSQL \(latestBinary.version)",
			binPath: latestBinary.binPath,
			varPath: varPath,
			startOnLogin: true
		)
		servers.insert(newDefaultServer, at: 0)
		saveServers()
		
		autocreatedVersions.append(latestBinary.version)
		UserDefaults.shared.set(autocreatedVersions, forKey: "AutoCreatedServerVersions")
	}
	
	
	func checkForExistingDataDirectories() {
		let dataDirsPath = FileManager.default.applicationSupportDirectoryPath()
		guard let dataDirsPathEnum = FileManager().enumerator(at: URL(fileURLWithPath: dataDirsPath), includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsSubdirectoryDescendants, .skipsPackageDescendants, .skipsHiddenFiles]) else { return }
		while let itemURL = dataDirsPathEnum.nextObject() as? URL {
			do {
				let resourceValues = try itemURL.resourceValues(forKeys: [.isDirectoryKey])
				guard resourceValues.isDirectory == true else { continue }
			} catch { continue }
			
			var dataDirHasServer = false
			for server in servers where server.varPath == itemURL.path { dataDirHasServer = true }
			
			if !dataDirHasServer {
				let dataDirName = itemURL.lastPathComponent
				let pgVersionPath = itemURL.appendingPathComponent("PG_VERSION").path
				
				do {
					var version = try String(contentsOfFile: pgVersionPath)
					version.removeLast() // remove \n
					let binary = BinaryManager.shared.getBinary(for: version)
					servers.append(Server(name: "PostgreSQL \(binary.version)", binPath: binary.binPath, varPath: itemURL.path))
					saveServers()
				} catch {
					NSLog("Import of data directory failed: No valid PG_VERSION file in \(dataDirName)")
				}
			}
		}
	}
}
