package ru.yandex.webmaster.common.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.Part;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * @author aherman
 */
public class FileParameter {
    private static final String MIME_APPLICATION_X_GZIP= "application/x-gzip";

    private final Part part;

    public FileParameter(Part part) {
        this.part = part;
    }

    @JsonIgnore
    public InputStream getInputStream() throws IOException {
        InputStream inputStream = part.getInputStream();
        if (MIME_APPLICATION_X_GZIP.equals(part.getContentType())) {
            inputStream = new GZIPInputStream(inputStream);
        }
        return inputStream;
    }

    public String getContentType() {
        return part.getContentType();
    }

    public String getName() {
        return part.getName();
    }

    public String getFileName() {
        String fileName = "";
        String header = part.getHeader("Content-Disposition");
        if (header != null) {
            String[] values = header.split(";");
            for (String value : values) {
                if (value.trim().startsWith("filename=")) {
                    String temp = value.trim().substring("fileName=".length());
                    fileName = temp.trim().replace("\"", "");
                    break;
                }
            }
        }
        return fileName;
    }

    public long getSize() {
        return part.getSize();
    }
}
