from django.db import models
from django.db.models import Max


class PresetProblemManager(models.Manager):

    def create(self, *args, **kwargs):
        from intranet.femida.src.problems.models import PresetProblem

        preset_problem = self.model(**kwargs)
        position = (
            PresetProblem.objects
            .filter(preset=preset_problem.preset)
            .aggregate(max_position=Max('position'))['max_position']
        )
        preset_problem.position = position + 1 if position is not None else 0
        preset_problem.save(force_insert=True)
        return preset_problem
