# -*- coding: utf-8 -*-
import logging
from renkanmanager import settings as renkan_settings
from renkanmanager.models import Revision
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Revision)
def revision_post_save(sender, instance, created, raw, using, update_fields, **kwargs):
    renkan = instance.parent_renkan
    parent_revisions = renkan.revisions.all()
    logger.debug("REVISIONS %r, INSTANCE %r, CURRENT %r", parent_revisions, instance, renkan.current_revision)

    if (not renkan.current_revision or renkan_settings.RENKAN_AUTO_CURRENT_REVISION) and parent_revisions.count() >= 1 and renkan.current_revision !=  parent_revisions[0]:
        logger.debug("CHANGE CURRENT REVISION OLD: %r , NEW: %r", renkan.current_revision, parent_revisions[0])
        renkan.current_revision = parent_revisions[0]
        renkan.save()
