from __future__ import with_statement
import org.sikuli.basics.SikuliXforJython
from sikuli import *
from sikuliwrapper import *
from org.sikuli.script import App, Env
from sikuli import Sikuli

#add custom image library
Sikuli.addImagePath(common.cfgImageLibrary)

class Calculator(BaseLogger):
	
	ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
	
	def __init__(self):
		self.appCoordinates = (0, 0, 1024, 768)
	
	def startApp(self):
		calcApp = App("Calculator")
		if not calcApp.window():
				App.open("calc.exe"); wait(2)
		calcApp.focus(); wait(1)

	def verifyApp(self):
		# check application
		if exists("CalcApp.png"):
			self.log.passed("Calculator window appeared")
		else:
			self.log.failed("No calculator window")

	def performAction(self, *args):
def _init():
    SikuliSettings.ActionLogs = False
    SikuliSettings.InfoLogs = False
    #SikuliSettings.DebugLogs = False

    #print "initializing"
    global myOS
    global _sitePackages
    global _logToFolder
    global _imageUpdating
    global _errorFile
    global _artifactFolder
    global _partialHTML
    global _myImagesPath
    global _showHeader
    global _textLog
    global _myEvent
    _myEvent = threading.Event()
    _myEvent.set()

    #OS-specific variables section
    my_OS = sikuli.Env.getOS()
    splitOSVersion = sikuli.Env.getOSVersion().split('.')
    my_OSVersion = splitOSVersion[0]+"."+splitOSVersion[1]
    if my_OS == sikuli.OS.LINUX:
        myOS = "L"
        _sikuliRepo = os.path.join(os.path.expanduser('~'),".Sikulix/")
        _vagrantFolder = "/vagrant/"
        _homeFolder = os.path.expanduser('~')+"/"
        os_options = {
        "3.2": "UbuntuPrecise",
        "3.13": "UbuntuTrusty",
        "4.4" : "UbuntuXenial",
        "3.8" : "Wasta12",
        "3.16": "Wasta14"
        }
    elif my_OS == sikuli.OS.WINDOWS:
        myOS = "W"
        _sikuliRepo = os.path.join(os.getenv('APPDATA'),"Sikulix\\")
        _vagrantFolder = "C:/vagrant/"
        _homeFolder = os.getenv('USERPROFILE')+"\\"
        os_options = {
        "6.0": "WindowsVista",
        "6.1":"Windows7",
        "6.2":"Windows8",
        "6.3":"Windows8.1",
        "10.0": "Windows10",
        }
    elif my_OS == OS.MAC:
        myOS = "M"
        _sikuliRepo = os.path.join(os.path.expanduser('~'),"Library/Application Support/Sikulix/")
        _homeFolder = os.path.expanduser('~')+"/"
    else:
        myOS = "N"
        print "Unsupported OS."
        exit(1)
    _sitePackages = os.path.join(_sikuliRepo, "Lib/site-packages")

    # Determine Logging Folder
    # A non-existent, empty, invalid logFolder.txt or one with "image_updater" keeps all logs in the .sikuli folder of each test.
    # A logFolder.txt with a valid path keeps all logs in one log in that folder.
    # A logFolder.txt with "vagrant" keeps all logs in the default vagrant folder.
    # Helper scripts logs are kept in the top level folder.
    try:
        with open(os.path.join(_sitePackages, "logFolder.txt"), "r") as f:
            rawLogFolder = os.path.normpath((f.readline()).strip())
    except IOError:
        rawLogFolder = "."

    if "image_updater" in rawLogFolder:
        _logToFolder = sikuli.getBundleFolder()
        updateImages()
        #setFindFailedResponse(PROMPT) #Native support for capturing in 1.1.1
    elif "vagrant" in rawLogFolder:
        _logToFolder = _vagrantFolder
    else:
        if rawLogFolder != "." and os.path.exists(rawLogFolder):
            _logToFolder = rawLogFolder
        else:
            if len(rawLogFolder)>1:
                print "ERROR: LogFolder.txt contents not usable. Using default behavior."
            _logToFolder = sikuli.getBundleFolder()
    Debug.setUserLogFile(os.path.join(_logToFolder, "UserLog.txt"), premake=False)

    try:
        myImagesFolder = os_options[my_OSVersion]
    except:
        sikuli.popup("The version of "+str(my_OS)+" is not supported yet.")

    #Determing where the common immage folders are and make them (default) if they are missing.
    parentPath = sikuli.getParentPath()
    parentFolder = os.path.basename(parentPath)
    if os.path.basename(parentPath) == "helpers":
        _myImagesPath = os.path.join(os.path.dirname(parentPath), "images", myImagesFolder)
    else:
        _myImagesPath = os.path.join(parentPath, "images", myImagesFolder)
    if not os.path.exists(_myImagesPath):
        error_message = "WARNING: The following Common Image Path is missing: "+_myImagesPath
        print error_message
        #sikuli.popup(error_message)
        if sikuli.Sikulix.prefLoad("cib") == "ASK":
            buttons = ["Make", "Cancel","Exit Program"]
            choice = JOptionPane().showOptionDialog(None, error_message , "Common Image Path Does Not Exist.",  JOptionPane.PLAIN_MESSAGE, 0, None, buttons, buttons[0])
        elif sikuli.Sikulix.prefLoad("cib") == "MAKE":
            choice = 0
        elif sikuli.Sikulix.prefLoad("cib") == "SKIP":
            choice = 1
        else:
            print "Common Image Behavior not correct."

        if choice == -1:
            pass #Window Closed
        elif choice == 0:
            #creat path
            try:
                os.makedirs(_myImagesPath)
                sikuli.addImagePath(_myImagesPath)
            except:
                sikuli.popup(_myImagesPath+" could not be created.")
        elif choice == 1:
            pass
        elif choice == 2:
            exit(1)
        else:
            #print "You added an extra button and it doesn't do anything."
            pass
    else:
        sikuli.addImagePath(_myImagesPath)

    #myProjectsPath = os.path.join(parentPath, "projects")

    # If a file with the given filename already exists, the Logger will
    # just keep writing to the end of that file.
    # *_errorFile* is the path to the text log.
    # *_logToFolder* is the path to the directory which stores the
    # html log and its assiocated images.
    _artifactFolder = os.path.join(_logToFolder, "log")
    _errorFile = os.path.join(_artifactFolder,"error_log")
    #with open(_errorFile, "a") as f:
    #    f.write("")

    # Create the log folder if it doesn't exist
    if not os.path.exists(_artifactFolder):
        os.makedirs(_artifactFolder)
        _partialHTML = os.path.join(_artifactFolder, "mylog.log")
    # Otherwise, see if there's already a log file
    else:
        glob_result = glob.glob(_artifactFolder + "/*.log")
        if len(glob_result) == 1:
            _partialHTML = glob_result[0]
        else:
            _partialHTML = os.path.join(_artifactFolder, "mylog.log")

    # Add the CSS stylesheet to the log folder, if it's not there already.
    if not os.path.exists(os.path.join(_artifactFolder, "log.css")):
        shutil.copyfile(os.path.join(_sitePackages,"log.css"),
                        os.path.join(_artifactFolder, "log.css"))
    if _showHeader:
        #if imported this header shows the filepath of the main script
        #if runScript this header shows the filepath of the helper script
        doc, tag, text = Doc().tagtext()
        with tag("tr"):
            with tag("td", style="text-align: center; background-color:lightskyblue", colspan="7"):
                text(time.strftime("%x %H:%M:%S")+": "+sikuli.getBundleFolder())
        with open(_partialHTML, "a") as f:
            f.write(doc.getvalue())
        _registerHTMLgenerator()