"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 04.01.22

"""
import datetime

from django.contrib.gis.db.models.functions import Area

from konova.management.commands.setup import BaseKonovaCommand
from konova.models import Geometry, Parcel, District


class Command(BaseKonovaCommand):
    help = "Checks the database' sanity and removes unused entries"

    def handle(self, *args, **options):
        try:
            self.update_all_parcels()
        except KeyboardInterrupt:
            self._break_line()
            exit(-1)

    def update_all_parcels(self):
        num_parcels_before = Parcel.objects.count()
        num_districts_before = District.objects.count()
        self._write_warning("=== Update parcels and districts ===")
        # Order geometries by size to process smaller once at first
        geometries = Geometry.objects.all().exclude(
            geom=None
        ).annotate(area=Area("geom")).order_by(
            'area'
        )
        self._write_warning(f"Process parcels for {geometries.count()} geometry entries now ...")
        i = 0
        num_geoms = geometries.count()
        for geometry in geometries:
            self._write_warning(f"--- {datetime.datetime.now()} Process {geometry.id} now ...")
            geometry.update_parcels()
            self._write_warning(f"--- Processed {geometry.get_underlying_parcels().count()} underlying parcels")
            i += 1
            self._write_warning(f"--- {i}/{num_geoms} processed")

        num_parcels_after = Parcel.objects.count()
        num_districts_after = District.objects.count()
        if num_parcels_after != num_parcels_before:
            self._write_error(f"Parcels have changed: {num_parcels_before} to {num_parcels_after} entries. You should run the sanitize command.")
        if num_districts_after != num_districts_before:
            self._write_error(f"Districts have changed: {num_districts_before} to {num_districts_after} entries. You should run the sanitize command.")

        self._write_success("Updating parcels done!")
        self._break_line()
