package com.airlock.iam.admin.app.infrastructure;

import com.vaadin.v7.data.util.converter.Converter;
import com.vaadin.v7.data.util.converter.DefaultConverterFactory;
import com.vaadin.v7.data.util.converter.Converter.ConversionException;
import java.io.File;
import java.util.Locale;

public class MedusaConverterFactory extends DefaultConverterFactory {
   public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType) {
      if (File.class.isAssignableFrom(modelType)) {
         return new MedusaConverterFactory.StringToFileConverter();
      } else {
         return Long.class.isAssignableFrom(modelType)
            ? new MedusaConverterFactory.StringToLongConverter()
            : super.createConverter(presentationType, modelType);
      }
   }

   private static class StringToFileConverter implements Converter<String, File> {
      public File convertToModel(String value, Class<? extends File> targetType, Locale locale) throws ConversionException {
         if (value != null && !value.isEmpty()) {
            File file = new File(value);
            if (file.exists()) {
               return file;
            } else {
               throw new ConversionException("The path " + value + " is not a valid file/directory.");
            }
         } else {
            return null;
         }
      }

      public String convertToPresentation(File value, Class<? extends String> targetType, Locale locale) throws ConversionException {
         return value != null ? value.getAbsolutePath() : null;
      }

      public Class<File> getModelType() {
         return File.class;
      }

      public Class<String> getPresentationType() {
         return String.class;
      }
   }

   private static class StringToLongConverter implements Converter<String, Long> {
      public Long convertToModel(String value, Class<? extends Long> targetType, Locale locale) throws ConversionException {
         if (value != null) {
            try {
               return Long.parseLong(value);
            } catch (NumberFormatException e) {
               throw new ConversionException("Unable to convert value '" + value + "' to Long.", e);
            }
         } else {
            return null;
         }
      }

      public String convertToPresentation(Long value, Class<? extends String> targetType, Locale locale) throws ConversionException {
         return value != null ? value.toString() : null;
      }

      public Class<Long> getModelType() {
         return Long.class;
      }

      public Class<String> getPresentationType() {
         return String.class;
      }
   }
}
