from .models import Calibration
from django import forms
from .schema import calibration_set_schema as calibset_schema
from jsonschema import validate
from jsonschema.exceptions import SchemaError, ValidationError as SchemaValidationError
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _

class CalibrationUpdateCreateForm(forms.ModelForm):
    class Meta:
        model = Calibration
        exclude = []

    calibration_data = forms.FileField(
        required=True,
        label=_('calibration data')
    )

    def clean(self):
        data = super(CalibrationUpdateCreateForm, self).clean()
        if 'calibration_data' in data:
            # json_data = data['calibration_data'].read()
            try:
                from json import loads as load_json

                data_as_str = data['calibration_data'].read().decode('utf-8')
                json_data = load_json(data_as_str)
                validate(json_data, calibset_schema)
                # it does indeed validate... just store it, the view is later on
                # responsible for parsing the data and create some fancy looks for it
            except SchemaError:
                raise ValidationError({'calibration_data': u'internal error, validation scheme invalid.'})
            except SchemaValidationError:
                raise ValidationError({'calibration_data': u'invalid file format, did not validate'})
            except:
                raise ValidationError({'calibration_data:': u'an error occurred while trying to read the file.'})
            from json import dumps

            data['calib_set_validated'] = dumps(json_data["calibration_set"])
            data['valid_to'] = json_data['valid_to']
            data['serial'] = json_data['serial']

        return data

    # keep in mind, this whole calibration set thing will only
    # work when operated via this form

    def save(self, commit=True):
        # throw the stuff we just validated from the uploaded file
        # into the json data text field
        self.object = super(CalibrationUpdateCreateForm, self).save(False)
        self.object.json_data = self.cleaned_data['calib_set_validated']
        self.object.valid_to = self.cleaned_data['valid_to']
        self.object.created_for = self.cleaned_data['serial']
        self.object.save()
        return self.object