# encoding: utf-8

# Copyright Peter Nowell

from __future__ import division, print_function, unicode_literals
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *
import traceback

fallbackCompanionPluginName = 'Font Proofer Companion'

# Version string, baked in at build time by buildPlugins.py via placeholder
# substitution. The single source of truth is pluginVersionString in buildPlugins.py.
pluginVersionString = '1.19'

def getFPPluginVersionNumber():
	"""Return this plugin's version string, e.g. '1.17'.

	From the Glyphs Macro Panel, the principal class is reachable through the
	ObjC runtime, so query the version with:

		import objc
		print(objc.lookUpClass('FontProoferCompanionPlugin').getFPPluginVersionNumber())
	"""
	return pluginVersionString

def showUnsupportedPythonAlert(pythonVersion):
	"""
	Pure-AppKit alert, scheduled onto the next main run loop pass
	so it never blocks the host app's startup / plugin loading.
	"""
	try :
		from AppKit import NSAlert, NSAlertStyleCritical
		from Foundation import NSOperationQueue
		def showAlert():
			alert = NSAlert.alloc().init()
			alert.setMessageText_( f'{fallbackCompanionPluginName} couldn’t load' )
			alert.setInformativeText_( f'Python {pythonVersion} isn’t supported by this version of {fallbackCompanionPluginName} (yet).\n\nPlease check for a Font Proofer update, or switch to another Python version.' )
			alert.setAlertStyle_(NSAlertStyleCritical)
			alert.addButtonWithTitle_('OK')
			alert.runModal()
		NSOperationQueue.mainQueue().addOperationWithBlock_(showAlert)
	except :
		try :
			print( traceback.format_exc() )
		except :
			print("—")

class FontProoferCompanionPlugin(GeneralPlugin):

	@classmethod
	def getFPPluginVersionNumber(cls):
		"""Plugin version string, exposed to ObjC so it can be called from the
		Glyphs Macro Panel via objc.lookUpClass('FontProoferCompanionPlugin').
		Deliberately NOT named version() — NSObject already defines that selector."""
		return pluginVersionString

	@objc.python_method
	def settings(self):
		self.name = fallbackCompanionPluginName

	@objc.python_method
	def start(self):	
		print("Starting Font Proofer companion plugin")
		try :
			import platform,sys,os
			arch = {'arm':'arm64','i386':'x86_64'}.get(platform.processor())
			binaryFolder = None
			if arch :
				binaryFolder = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)),'fpcompanion/versions'),arch+"_"+(str(sys.version_info[0])+str(sys.version_info[1])))
			if binaryFolder is None or not os.path.isdir(binaryFolder) :
				showUnsupportedPythonAlert( str(sys.version_info[0])+'.'+str(sys.version_info[1]) )
				print( f'{fallbackCompanionPluginName} doesn’t support Python {sys.version_info[0]}.{sys.version_info[1]} on this architecture (yet), so it won’t load.' )
				return
			sys.path.insert(0,binaryFolder)
		except :
			print( f'{fallbackCompanionPluginName} had some trouble starting up :(' )
			try :
				print( traceback.format_exc() )
			except :
				print("—")
		
		try :
			from fpcompanion import companion
		except :
			print( f'{fallbackCompanionPluginName} had some trouble loading :(' )
			try :
				print( traceback.format_exc() )
			except :
				print("—")
		
		try :
			fpcInstance = companion.FontProoferCompanion()
			fpcInstance.start()
		except :
			print( f'{fallbackCompanionPluginName} had some trouble starting :(' )
			try :
				print( traceback.format_exc() )
			except :
				print("—")

	@objc.python_method
	def __file__(self):
		"""Please leave this method unchanged"""
		return __file__
