from .s32_region_util import calculate_boundary, inflate_boundary
from .s33_dma_cal import *
from .s33_dma import get_all_district_metering_area_ids, get_all_district_metering_areas, get_district_metering_area, is_descendant_of
from .batch_exe import execute_batch_command


def generate_district_metering_area(name: str, part_count: int = 1, part_type: int = PARTITION_TYPE_RB, inflate_delta: float = 0.5) -> ChangeSet:
    cs = ChangeSet()

    dmas = get_all_district_metering_areas(name)
    max_level = 0
    for dma in dmas:
        if dma['level'] > max_level:
            max_level = dma['level']
    while max_level > 0:
        for dma in dmas:
            if dma['level'] == max_level:
                cs.delete({ 'type': 'district_metering_area', 'id': dma['id'] })
        max_level -= 1

    i = 1
    for nodes in calculate_district_metering_area_for_network(name, part_count, part_type):
        boundary = calculate_boundary(name, nodes)
        boundary = inflate_boundary(name, boundary, inflate_delta)
        cs.add({ 'type': 'district_metering_area', 'id': f"DMA_1_{i}", 'boundary': boundary, 'parent': None, 'nodes': nodes })
        i += 1

    return execute_batch_command(name, cs)


def generate_sub_district_metering_area(name: str, dma: str, part_count: int = 1, part_type: int = PARTITION_TYPE_RB, inflate_delta: float = 0.5) -> ChangeSet:
    cs = ChangeSet()

    for id in get_all_district_metering_area_ids(name):
        if is_descendant_of(name, id, dma):
            cs.delete({ 'type': 'district_metering_area', 'id': id })

    level = get_district_metering_area(name, dma)['level'] + 1

    i = 1
    for nodes in calculate_district_metering_area_for_region(name, dma, part_count, part_type):
        boundary = calculate_boundary(name, nodes)
        boundary = inflate_boundary(name, boundary, inflate_delta)
        cs.add({ 'type': 'district_metering_area', 'id': f"DMA_[{dma}]_{level}_{i}", 'boundary': boundary, 'parent': dma, 'nodes': nodes })
        i += 1

    return execute_batch_command(name, cs)
