# -*- coding: UTF-8 -*-
from celery import shared_task
from .models import *


@shared_task
def handle_viewmodel_sync(vm_cls, ids):
    if isinstance(vm_cls, (str, unicode)):
        vm_cls = globals().get(vm_cls)
    objs = vm_cls.rel_model.objects.filter(id__in=ids)
    obj_ids = objs.values_list('id', flat=True)
    vms = vm_cls.objects.filter(id__in=ids)
    vm_ids = vms.values_list('id', flat=True)

    ids_not_exist = set(ids) - set(obj_ids)
    if ids_not_exist:
        vm_cls.objects.filter(id__in=ids_not_exist).delete()

    vm_cls.prefetch(objs)
    for obj in objs:
        if obj.id not in vm_ids:
            # 不存在, 先实例化viewmodel
            vm = vm_cls()
        else:
            vm = vms.get(id=obj.id)
        vm.save_from_object(obj)



@shared_task
def hera_diary_sync(diary_ids):
    objs = DiaryVM.rel_model.objects.filter(id__in=diary_ids)
    obj_ids = objs.values_list('id', flat=True)
    vms = DiaryVM.objects.filter(id__in=diary_ids)
    vm_ids = vms.values_list('id', flat=True)

    ids_not_exist = set(diary_ids) - set(obj_ids)
    if ids_not_exist:
        DiaryVM.objects.filter(id__in=ids_not_exist).delete()

    DiaryVM.prefetch(objs)
    for obj in objs:
        if obj.id not in vm_ids:
            # 不存在, 先实例化viewmodel
            vm = DiaryVM()
        else:
            vm = vms.get(id=obj.id)
        vm.save_from_object(obj)
