# -*- coding: utf-8 -*-

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

from tendo import singleton

from mtp.apps.sync.models import Task


class Command(BaseCommand):
    args = ''
    help = 'Execute all pending tasks.'

    def handle(self, *args, **options):
        me = singleton.SingleInstance()

        if settings.INSTANCE_IS_MASTER:
            return

        tasks = Task.objects.filter(done=False)
        tc = tasks.count()
        tcd = 0
        for task in tasks:
            count = 0
            while count < 3:
                print(task.path)
                if task.launch():
                    print("done")
                    break
                else:
                    print("Error, retying")
                    count += 1

            if count == 3:
                print("To more retry")
                continue

            print(task.finish_path)
            if task.finish():
                print("Task completed")
                tcd += 1
                task.done = True
                task.save()

        print("%d tasks applied, %d tasks to apply" % (tcd, tc - tcd))
