#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2021, Nils Hilbricht, Germany ( https://www.hilbricht.net )

This file is part of the Laborejo Software Suite ( https://www.laborejo.org ),

This application is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import logging; logger = logging.getLogger(__name__); logger.info("import")


import os.path
#from code import InteractiveInterpreter
import engine.api as api

class DebugScriptRunner(object):
    """We do not provide our own text editor in the GUI. Instead the user must edit debugscript.py
    in our NSM Session directory, save and then self.run"""

    def __init__(self, apilocals):
        super().__init__()
        self.apilocals = apilocals
        self.absoluteScriptFilePath = None

    def trueInit(self, nsmClient):
        assert nsmClient
        self.nsmClient = nsmClient
        self.absoluteScriptFilePath = os.path.join(self.nsmClient.ourPath, "debugscript.py")
    
    def _createEmptyDebugScript(self):
        assert self.absoluteScriptFilePath
        logger.info(f"{self.nsmClient.ourClientNameUnderNSM}: Script file not found. Initializing: {self.absoluteScriptFilePath}")
        text = ("""#! /usr/bin/env python3"""
        "\n"
        """# -*- coding: utf-8 -*-"""
        "\n"
        "#This file is in the Qt-MainWindow (-> self) scope.\n#You can also call api commands which will trigger a GUI callback. Like api.undo(), api.redo() etc."
        "\n"
        """print ("Hello World")"""
        "\n"
        )

        with open(self.absoluteScriptFilePath, "w", encoding="utf-8") as f:
            f.write(text)       
    
    def run(self):
        if not os.path.exists(self.absoluteScriptFilePath):
            if not os.path.exists(self.nsmClient.ourPath):
                os.makedirs(self.nsmClient.ourPath)        
            self._createEmptyDebugScript()
        
        try:
            exec(compile(open(self.absoluteScriptFilePath).read(), filename=self.absoluteScriptFilePath, mode="exec"), globals(), self.apilocals)
        except Exception as e:
            print (e)

        #with open(self.absoluteScriptFilePath, "r", encoding="utf-8") as f:
        #    source = f.read()
        #self.runsource(source=source, filename=self.absoluteScriptFilePath)
