# -*- 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 threading
import queue
import re
import time

import cpipe
import LogMsg

# ==============================================================================
class PipeWriter:
    def __init__(self, trace, qStatus,pipename, fct_IsAlive ):
        self.running       = True
        self.qStatus       = qStatus
        self.tr            = trace
        self.pipename      = pipename
        self.pipeout       = None
        self.IsAlive       = fct_IsAlive

    def Start(self):
        self.tr.info("PipeWriter "+ _("is started"))
        self.pipeout = cpipe.cpipe('w',self.tr)
        if not self.pipeout.open(self.pipename) :
            self.tr.error("PipeWriter "+ _("is aborted"))
            return False
        return True


    def Put(self,line):
        if self.pipeout is None :
            return False

        mEmpty   = re.match(r'^[ \t]*$',line.rstrip() )
        mComment = re.match(r'^[ \t]*#',line.rstrip() )
        if (mEmpty is not None) or (mComment is not None ) :
            self.tr.cmdsiril( _("not processed") + ": '" + line + "'")
        else:
            self.tr.cmdsiril(line.rstrip() )
            if not self.pipeout.write( line ):
                self.running = False
                self.tr.error("Abort pipeout.write()")
                raise Exception()
            status=self.getStatus()
            self.tr.cmdsiril( "[" + status +"]")
            self.tr.DisplayMsgQueue()
            if status != "status: success" :
                return False
        return True

    def Stop(self):
        if self.pipeout is None :
            return False
        self.tr.info(_("Stopping") +" PipeWriter ...")
        self.pipeout.write( "close\n" )
        time.sleep(1)
        self.pipeout.write( "exit\n" )
        time.sleep(1)
        self.running = False
        self.pipeout.close()
        self.pipeout = None
        self.tr.info("PipeWriter "+ _("is stopped"))

    def IsRunning(self):
        return self.running

    def getStatus(self):
        while self.running :
            self.tr.DisplayMsgQueue()
            while self.qStatus.qsize( ):
                try:
                    status =self.qStatus.get(0)
                    self.tr.DisplayMsgQueue()
                    return status
                except queue.Empty:
                    pass
            if not self.IsAlive():
                return "abort"
            time.sleep(0.1)
        return "abort"
