
package de.ivu.elect.jee.faces.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.FilenameUtils;
import org.primefaces.model.UploadedFile;

/**
 * This class wraps an instance of {@link org.primefaces.model.UploadedFile UploadedFile} and is used to provide a
 * canonical filename for the file uploads since the filename format varies between browsers.
 * 
 * The normalization is done using {@link org.apache.commons.io.FilenameUtils FilenameUtils}.
 * 
 */
public class UploadedFileWithCanonicalFilename implements UploadedFile {

  private UploadedFile uploadedFile;

  public UploadedFileWithCanonicalFilename(UploadedFile uploadedFile) {
    this.uploadedFile = uploadedFile;
  }

  @Override
  public String getFileName() {
    return FilenameUtils.getName(uploadedFile.getFileName());
  }

  @Override
  public List<String> getFileNames() {
    List<String> result = uploadedFile.getFileNames();
    if (result==null){
      return null;
    }
    return result.stream().map(FilenameUtils::getName).collect(Collectors.toList());
  }

  @Override
  public InputStream getInputstream() throws IOException {
    return uploadedFile.getInputstream();
  }

  @Override
  public long getSize() {
    return uploadedFile.getSize();
  }

  @Override
  public byte[] getContents() {
    return uploadedFile.getContents();
  }

  @Override
  public String getContentType() {
    return uploadedFile.getContentType();
  }

  @Override
  public void write(String s) throws Exception {
    uploadedFile.write(s);
  }

}
