from django.core.management.base import BaseCommand
from django.contrib.gis.utils import LayerMapping

from glob import iglob
from pathlib import Path
from zipfile import ZipFile, is_zipfile

import right_tree.api.data
from right_tree.api.models import SoilLayer, EcologicalDistrictLayer, ChristchurchRegion

# Auto-generated `LayerMapping` dictionary for SoilLayers model
soillayer_mapping = {
    'nzsc_class': 'nzsc_class',
    'nzsc_group': 'nzsc_group',
    'nzsc_order': {'code': 'nzsc_order'},
    'shape_leng': 'SHAPE_Leng',
    'geom': 'POLYGON',
}

# Auto-generated `LayerMapping` dictionary for ecologicaldistrictlayer model
ecologicaldistrictlayer_mapping = {
    'ecological': 'ECOLOGICAL',
    'ecologic_1': 'ECOLOGIC_1',
    'ecologic_2': {'name': 'ECOLOGIC_2'},
    'shape_leng': 'SHAPE_Leng',
    'shape_area': 'SHAPE_Area',
    'geom': 'POLYGON',
}

# Auto-generated `LayerMapping` dictionary for ChristchurchRegion model
christchurchregion_mapping = {
    'objectid': 'OBJECTID',
    'name': 'NAME',
    'geom': 'MULTIPOLYGON',
}

resources_path = Path(right_tree.api.data.__file__).resolve().parent / "resources"

soillayer_shp = resources_path / "fundamental-soil-layers-new-zealand-soil-classification.shp"
ecologicaldistrictlayer_shp = resources_path / "Ecological_Districts.shp"
christchurchregion_shp = resources_path / "Greater_Christchurch_Area.shp"


class Command(BaseCommand):
    help = 'Ingests the shapefile data for ecological regions and soil layers.'

    def handle(self, *args, **options):
        query = str(resources_path / "*.zip")
        sources = [ZipFile(path) for path in iglob(query) if is_zipfile(path)]

        for zf in sources:
            zf.extractall(resources_path)
            zf.close()

        self.stdout.write('Loading soil layers...')
        soil_lm = LayerMapping(SoilLayer, soillayer_shp, soillayer_mapping, transform=False)
        soil_lm.save(strict=True)
        self.stdout.write(self.style.SUCCESS('Soil layers loaded succesfully.'))

        self.stdout.write('Loading ecological district layers...')
        ecologicaldistrictlayer_lm = LayerMapping(EcologicalDistrictLayer, ecologicaldistrictlayer_shp, ecologicaldistrictlayer_mapping, transform=False)
        ecologicaldistrictlayer_lm.save(strict=True)
        self.stdout.write(self.style.SUCCESS('Ecological district layers loaded succesfully.'))

        self.stdout.write('Loading christchurch zone layer...')
        christchurchregionlayer_lm = LayerMapping(ChristchurchRegion, christchurchregion_shp, christchurchregion_mapping, transform=False)
        christchurchregionlayer_lm.save(strict=True)
        self.stdout.write(self.style.SUCCESS(' Christchurch zone layer loaded succesfully.'))
