from datetime import datetime

from django.db.models import Q

from staff.person.models import Staff

from .models import LentaLog
from .objects import Aggregator, Archaeologist


def fill_office_and_organizations():
    offices = dict(
        Staff.objects.values_list('id', 'office_id').iterator()
    )
    organizations = dict(
        Staff.objects.values_list('id', 'organization_id').iterator()
    )

    query = LentaLog.objects.filter(
        Q(office_old=None, office_new=None) |
        Q(organization_old=None, organization_new=None)
    )
    count = query.count()
    query_iterator = query.iterator()

    for num, record in enumerate(query_iterator):
        if record.office_old is None and record.office_new is None:
            if record.action != 'h':
                record.office_old_id = offices[record.staff_id]
            record.office_new_id = offices[record.staff_id]

        if record.organization_old is None and record.organization_new is None:
            if record.action != 'h':
                record.organization_old_id = organizations[record.staff_id]
            record.organization_new_id = organizations[record.staff_id]

        record.save()
        print('fill_office_and_organizations: %d%%' % (num * 100 // count))


def fill_hirements_and_dismissals():
    # Заполнить ленту в прошлом данными о наймах
    for t in enumerate(Archaeologist.fill_missing_hirements()):
        print(t)

    # Заполнить ленту в прошлом данными об увольнениях
    for t in enumerate(Archaeologist.fill_missing_dismissals()):
        print(t)


def fill_counters():
    aggr = Aggregator(datetime(1990, 1, 1), datetime.now())
    aggr.run()


def do_all_stuff():
    fill_office_and_organizations()
    fill_hirements_and_dismissals()
    fill_counters()
