from django.core.management.base import BaseCommand
from django.conf import settings

from ...models.replication import ReplicationSource, ReplicationTarget
from ...classes.replication import ContentMonsterDatabase

from contentmonster.classes.config import MonsterConfig
from contentmonster.classes.vesselthread import VesselThread
from contentmonster.classes.shorethread import ShoreThread

from multiprocessing import Manager

import time

  
class Command(BaseCommand):
    help = 'Runs the file replication service (ContentMonster)'
  
    def handle(self, *args, **kwargs):
        config = MonsterConfig()

        for source in ReplicationSource.objects.all():
            config.directories.append(source.to_directory())

        for target in ReplicationTarget.objects.all():
            config.vessels.append(target.to_vessel(dbclass=ContentMonsterDatabase))

        with Manager() as manager:
            state = manager.dict()
            state["files"] = manager.list()
            state["config"] = config

            threads = []

            for vessel in config.vessels:
                thread = VesselThread(vessel, state, dbclass=ContentMonsterDatabase)
                thread.start()
                threads.append(thread)

            shore = ShoreThread(state, dbclass=ContentMonsterDatabase)
            shore.start()

            while True:
                try:
                    time.sleep(10)
                except KeyboardInterrupt:
                    print("Keyboard interrupt received - stopping threads")
                    shore.terminate()
                    for thread in threads:
                        thread.terminate()
                    exit()