from flask_wtf.file import FileField, FileRequired
from wtforms import ValidationError
from app.services import SERVICES
from ..forms import ContributionBaseForm, EditContributionBaseForm


class CreateTesseractOCRPipelineModelForm(ContributionBaseForm):
    tesseract_model_file = FileField(
        'File',
        validators=[FileRequired()]
    )
    
    def validate_tesseract_model_file(self, field):
        if not field.data.filename.lower().endswith('.traineddata'):
            raise ValidationError('traineddata files only!')

    def __init__(self, *args, **kwargs):
        service_manifest = SERVICES['tesseract-ocr-pipeline']
        super().__init__(*args, **kwargs)
        self.compatible_service_versions.choices = [('', 'Choose your option')]
        self.compatible_service_versions.choices += [
            (x, x) for x in service_manifest['versions'].keys()
        ]
        self.compatible_service_versions.default = ''


class EditTesseractOCRPipelineModelForm(EditContributionBaseForm):
    def __init__(self, *args, **kwargs):
        service_manifest = SERVICES['tesseract-ocr-pipeline']
        super().__init__(*args, **kwargs)
        self.compatible_service_versions.choices = [('', 'Choose your option')]
        self.compatible_service_versions.choices += [
            (x, x) for x in service_manifest['versions'].keys()
        ]
        self.compatible_service_versions.default = ''
