# Copyright (C) 2023 Stefy Lanza <stefy@nexlab.net> and SexHack.me
#
# This program 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 <https://www.gnu.org/licenses/>.
import time
import sys
from utils import create_daemon
import queue
import logging

logging.getLogger(__name__)

STATUSES=[
      'manual',
      'automatic'
      ]


class TaskEngine():

    status='manual'
    scene='manual'

    def set_manual(self, manual=True):
        nst = False
        if manual and self.status != 'manual':
           nst = 'manual'
        elif not manual and self.status == 'manual':
           nst = 'automatic'
        if nst:
           logging.info('CHANGE STATUS TO '+nst)
           self.status=nst
           evt={'event': 'STATUSCHANGE', 'data':{'status': nst}}
           qpnl.put(evt)
           qweb.put(evt)

    def process_task(self, task):
        event = task['event']
        if 'data' in task.keys():
            data = task['data']
        if event=='SETSTATUS' and data['status'] in ['manual','automatic']:
            if self.status != data['status']:
            	self.set_manual(data['status']=='manual')
        elif event=='CHANGESTATUS':
            self.set_manual(self.status!='manual')
            #if self.status == 'manual':
            #    self.set_manual(False)
            #else:
            #    self.set_manual(True)
        elif event in ['OUTPUTCHANGE', 'INPUTSTATUSCHANGE']:
            qpnl.put(task)
            qweb.put(task)
   


def camstudio():
    engine=TaskEngine()
    while True:
        task = qcore.get(block=True)
        if task:
           logging.info(task)
           engine.process_task(task)
           qcore.task_done()
        time.sleep(.001)


def run_camstudio(daemon=False):
    if daemon and sys.platform != 'win32':
        create_daemon()
    camstudio()
