# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2021 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import copy
import hashlib
import uuid
import zipfile

from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.text import slugify
from django.views.generic import DetailView

from .models import ToulouseSmartResource


class TypeIntervention(DetailView):
    model = ToulouseSmartResource
    template_name = 'toulouse_smart/type-intervention.html'


class TypeInterventionAsBlocks(DetailView):
    model = ToulouseSmartResource

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        def make_id(s):
            return str(uuid.UUID(bytes=hashlib.md5(s.encode()).digest()))

        # generate file contents
        files = {}
        # do not alter the cached intervention_types
        intervention_types = copy.deepcopy(self.object.get_intervention_types())
        for intervention_type in intervention_types:
            slug = slugify(intervention_type['name'])
            # only export intervention_type with properties
            if not intervention_type.get('properties'):
                continue
            for prop in intervention_type['properties']:
                # generate a natural id for fields
                prop['id'] = make_id(slug + slugify(prop['name']))
                prop['varname'] = slugify(prop['name']).replace('-', '_')
                # adapt types
                prop.setdefault('type', 'string')
                if prop['type'] == 'boolean':
                    prop['type'] = 'bool'
                if prop['type'] == 'int':
                    prop['type'] = 'string'
                    prop['validation'] = 'digits'
            filename = 'block-%s.wcs' % slug
            files[filename] = render_to_string('toulouse_smart/wcs_block.wcs', context=intervention_type)

        # zip it !
        response = HttpResponse(content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=blocks.zip'
        with zipfile.ZipFile(response, mode='w') as zip_file:
            for name, f in files.items():
                zip_file.writestr(name, f)

        return response
