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

import LogMsg

# ==============================================================================
class ThreadReader(threading.Thread):
    def __init__(self,trace,qStatus, pipename , fct_IsAlive):
        threading.Thread.__init__(self)
        self.running       = True
        self.qStatus       = qStatus
        self.tr            = trace
        self.pipename      = pipename
        self.memo          = []
        self.IsAlive       = fct_IsAlive

    def run(self):
        self.tr.info("ThreadReader "+ _("is started"))
        pipein = cpipe.cpipe('r',self.tr)
        if not pipein.open(self.pipename) :
            self.tr.error("ThreadReader "+ _("is aborted"))
            self.running = False
            return
        memo_no_processed=""
        try:
            while self.running:
                try:
                    lines = pipein.read()
                    if lines == None :
                        self.tr.info("ThreadReader is aborted")
                        self.running = False
                        break
                    lines = memo_no_processed + lines
                    noCr = len(lines) > 0 and lines[-1] !="\n"
                    lines_split= lines.split('\n')
                    nb=len(lines_split)
                    if noCr : nb-=1
                    for ii in range(nb):
                        line = lines_split[ii]
                        if len(line) !=0 :
                            self.memo.append(line)
                        if len(line) != 0 :
                            #print( '>> %s'  % line )
                            if line[0:6] == 'status' :
                                if line[0:16] == 'status: starting':
                                    pass
                                if line[0:15] == 'status: success':
                                    self.qStatus.put('status: success')
                                if line[0:13] == 'status: error':
                                    self.tr.info( line )
                                    self.qStatus.put('status: error')
                            else:
                                if line[0:8] == 'progress' :
                                    #self.queue_Progress.put(line)
                                    pass
                                else:
                                    #print("**"+line.rstrip()+"**")
                                    self.tr.retoursiril( line.rstrip() )
                        else:
                            time.sleep(0.1)
                    if noCr :
                        memo_no_processed= lines_split[-1]
                    else:
                        memo_no_processed=""
                    if not self.IsAlive():
                        self.tr.info("ThreadReader "+ _("is aborted"))
                        self.running = False
                        break

                except OSError:
                    # the os throws an exception if there is no data
                    time.sleep(0.1)
                    pass
        except (KeyboardInterrupt, SystemExit):
            sys.exit()
        except Exception as e :
            self.tr.error("*** ThreadReader::run() " + str(e)+"\n")

        pipein.close()
        self.tr.info("ThreadReader "+ _("is stopped"))

    def GetCR(self):
        return self.memo

    def ClrCR(self):
        self.memo = []

    def IsRunning(self) :
        return self.running

    def Stop(self):
        if self.running :
            self.tr.info( _("Stopping") +" ThreadReader ...")
        self.running = False

