# coding: utf-8


import logging

from idm.notification.utils import report_problem
from idm.services.models import Service
from idm.utils.lock import lock

log = logging.getLogger(__name__)


def sync_services_async():
    from idm.services.tasks import SyncServices
    SyncServices.delay()


def sync_services():
    result = False
    with lock('idm.services.tasks.SyncServicesTask', block=False) as acquired:
        if not acquired:
            log.info('Service synchronization cannot be started: lock cannot be acquired')
            return result

        root = Service.objects.get_root()

        log.info('Starting service synchronization')
        try:
            root.synchronize()
        except Exception as exc:
            log.exception('Service syncronization failed')

            report_problem(
                'Проблема с синхронизацией сервисов',
                ['emails/service/service_sync_error.txt'],
                {'exception_type': type(exc).__name__}
            )
        else:
            log.info('Service synchronization has successfully finished')
            result = True

    return result
