# -*- coding: UTF-8 -*-
# ==============================================================================

# ------------------------------------------------------------------------------
# Project: pysiril ( Python SiriL )
#
# This is a library to interface python to Siril.
# ------------------------------------------------------------------------------
#    Author:  M27trognondepomme <pebe92 (at) gmail.com>
#
# This program is provided without any guarantee.
#
# The license is  LGPL-v3
# For details, see GNU General Public License, version 3 or later.
#                        "https://www.gnu.org/licenses/gpl.html"
# ------------------------------------------------------------------------------

import sys
import os
import time
import queue
import threading
from   inspect import getframeinfo, stack

# ==============================================================================

class trace:
    def __init__(self):
        self.bLog      = True
        self.bInfo     = True
        self.bWarning  = True
        self.bError    = True
        self.bMuteSiril= False
        self.bLineFile = False

        self.translation = "".maketrans("������","eeecau")
        self.fdlog       = None
        self.qMsg        = queue.Queue()
        self.duree       = 0.100
        self.stop        = False
        #self.timerLog    = threading.Timer(self.duree/2, self.periodicCallRxLog )
        #self.timerLog.start()

    def Configure(self, bLog,bInfo,bWarning,bError):
        self.bLog     = bLog
        self.bInfo    = bInfo
        self.bWarning = bWarning
        self.bError   = bError

    # --------------------------------------------------------------------------
    def MuteSiril(self, bValue=True ):
        self.bMuteSiril=bValue

    def AddLineFilename(self,bFlag):
        self.bLineFile  = bFlag

    def Stop(self):
        if self.bInfo :
            self.Write("Stopping Trace ...")
        self.stop=True
        try:
            buffer = self.Depile()
            self.Write(buffer)
        except:
            pass
        if self.bInfo :
            self.Write("Trace is stopped")


    def Logfile(self, enable , workdir= "" ) :
        if enable :
            if self.fdlog is not None :
                try:
                    self.fdlog.close()
                except:
                    self.fdlog =None
            logfilename = os.path.join(workdir,'pysiril.log' )
            try:
                self.fdlog  = open(logfilename,"w")
            except Exception as e :
                print("*** trace::Logfile() : ",e)
                print("*** Error open logfile :", logfilename+"\n")
                self.fdlog =None
        else:
            if self.fdlog is not None :
                try:
                    self.fdlog.close()
                except:
                    pass
            self.fdlog = None


    def Depile(self):
        buffer = ""
        status=False
        debut=time.time()
        while self.qMsg.qsize( ):
            try:
                msg=self.qMsg.get(0)
                if len(buffer) != 0 :
                    buffer = buffer + "\n" + msg
                else:
                    buffer = msg
            except queue.Empty:
                print("*** empty")
                pass
            if (time.time() - debut) > self.duree :
                status=True
                break
        return status,buffer

    def DisplayMsgQueue(self):
        status,bufferQueue = self.Depile()
        self.WriteRaw(bufferQueue)

    def Write(self,buffer=""):
        self.DisplayMsgQueue
        self.WriteRaw(buffer)

    def WriteRaw(self, buffer):
        if buffer != "" :
            buffer = buffer.translate(self.translation) # suppression des accents du log
            print( buffer )
            if self.fdlog is not None :
                self.fdlog.write(buffer)
                self.fdlog.flush()

    def log(self,message,bQueue=False):
        if self.bLineFile :
            caller = getframeinfo(stack()[1][0])
            message = "- %s:%d - %s" % (caller.filename, caller.lineno, message)
        if self.bLog :
            self.display("LOG    ",message,bQueue)

    def info(self,message,bQueue=False):
        if self.bLineFile :
            caller = getframeinfo(stack()[1][0])
            message = "- %s:%d - %s" % (caller.filename, caller.lineno, message)
        if self.bInfo :
            self.display("INFO   ",message,bQueue)

    def warning(self,message,bQueue=False):
        if self.bLineFile :
            caller = getframeinfo(stack()[1][0])
            message = "- %s:%d - %s" % (caller.filename, caller.lineno, message)
        if self.bWarning :
            self.display("WARNING",message,bQueue)

    def error(self,message,bQueue=False):
        if self.bLineFile :
            caller = getframeinfo(stack()[1][0])
            message = "- %s:%d - %s" % (caller.filename, caller.lineno, message)
        if self.bError :
            self.display("ERROR  ",message,bQueue)

    def cmdsiril(self,cmdstr):
        if not self.bMuteSiril :
            self.PutQueueMsg("> " + cmdstr)

    def retoursiril(self,cmdstr):
        if not self.bMuteSiril :
            self.PutQueueMsg(": " + cmdstr)

    def display(self,level,message,bQueue=False):
        msgfmt=level+ ": "+message
        if bQueue :
            self.PutQueueMsg(msgfmt)
        else:
            self.Write(msgfmt)

    def PutQueueMsg(self,message):
        self.qMsg.put(message)

