/*-
 * ~~~~~~licensing~~~~~~
 * file-upload
 * ==========
 * Copyright (C) 2020 - 2022 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.management.file.upload;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.ws.rs.core.MultivaluedMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class FileUploadProcessor implements Processor {

    private static final Logger log = LoggerFactory.getLogger(FileUploadProcessor.class);

    @Override
    public void process(Exchange exchange) throws Exception {
        Attachment attachment = exchange.getIn().getBody(Attachment.class);
        String fileName = "unknown";
        DataHandler dataHandler = attachment.getDataHandler();
        UUID id = UUID.randomUUID();

        InputStream inputStream = null;
        OutputStream out = null;
        try {
            String path = System.getProperty("karaf.data") + "/local-repo/";
            if (new File(path + id.toString() + "/").mkdir()) {
                path += id.toString() + "/";

                inputStream = dataHandler.getInputStream();
                MultivaluedMap<String, String> map = attachment.getHeaders();
                fileName = getFileName(map);
                out = new FileOutputStream(new File(path + fileName));
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
            }
        } catch (Exception e) {
            log.error("Error while upload file: " + e.getMessage());
        } finally {
            inputStream.close();
            out.flush();
            out.close();
        }
        exchange.getMessage().setBody(id.toString());
    }

    private String getFileName(MultivaluedMap<String, String> header) {
        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                String exactFileName = name[1].trim().replaceAll("\"", "");
                return exactFileName;
            }
        }
        return "unknown";
    }
}
