#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright (c) 2010-2012 The Orca Team
# Copyright (c) 2012 Igalia, S.L.
# Copyright (c) 2005-2010 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA  02110-1301 USA.
#
# Fork of Orca Screen Reader (GNOME)
# Original source: https://gitlab.gnome.org/GNOME/orca

import argparse
import dbus
import dbus.service
import sys

from cthulhu import cthulhu
from dbus.mainloop.glib import DBusGMainLoop

class LoggerService(dbus.service.Object):

    def __init__(self, filePrefix):
        self._logger = cthulhu.getLogger()
        self._logNames = ['braille', 'speech']
        self._filePrefix = filePrefix

        DBusGMainLoop(set_as_default=True)
        busname = dbus.service.BusName('org.gnome.Cthulhu', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, busname, '/org/gnome/Cthulhu')

    @dbus.service.method(dbus_interface='org.gnome.Cthulhu.Logger', in_signature='', out_signature='')
    def startRecording(self):
        for name in self._logNames:
            self._logger.clearLog(name)

    @dbus.service.method(dbus_interface='org.gnome.Cthulhu.Logger', in_signature='', out_signature='s')
    def stopRecording(self):
        contents = ''
        for name in self._logNames:
            content = self._logger.getLogContent(name)
            contents += content
            fileName = open('%s.%s' % (self._filePrefix, name), 'a', encoding='utf-8')
            fileName.writelines(content)
            fileName.close()

        return contents

def main():
    sys.argv[0] = 'cthulhu'

    parser = argparse.ArgumentParser()
    parser.add_argument("-u", "--user-prefs", action="store")
    parser.add_argument("--debug-file", action="store")
    args = parser.parse_args()

    cthulhu.debug.debugFile = open('%s.debug' % args.debug_file, 'w')

    manager = cthulhu.getSettingsManager()
    manager.activate(args.user_prefs)
    sys.path.insert(0, manager.getPrefsDir())

    service = LoggerService(args.debug_file)

    return cthulhu.main()

if __name__ == "__main__":
    sys.exit(main())
