/*
 * Atlassian Source Code Template.
 * User: mike
 * Date: Dec 20, 2001
 * Time: 11:16:30 AM
 * CVS Revision: $Revision: 1.6 $
 * Last CVS Commit: $Date: 2002/04/30 14:51:53 $
 * Author of last CVS Commit: $Author: mike $
 */
package com.atlassian.jira.web.action.issue;

import com.atlassian.jira.util.AttachmentUtils;
import org.ofbiz.core.entity.GenericValue;
import webwork.action.PrepareAction;
import webwork.action.factory.ActionFactory;
import webwork.action.standard.FileUpload;
import webwork.util.UploadedFile;

import java.io.File;

public class AttachFile extends ViewIssue implements PrepareAction
{
	UploadedFile file = null;

	public void prepare() throws Exception
	{
        long startTime = System.currentTimeMillis();
		log.debug("AttachFile.prepare");

		// check that the directory to put the attachment in exists
		File tempDirectory = AttachmentUtils.getTempDirectory();

		FileUpload fileUpload = (FileUpload) ActionFactory.getAction("PellFileUpload");
		fileUpload.setSaveDir(tempDirectory.getAbsolutePath());
		fileUpload.setMaxSize(20 * 1024 * 1024); // default to 20 megs
		fileUpload.autoSetParameters(this);

        log.info("Time taken to process attachment " + (System.currentTimeMillis() - startTime) + " ms");
	}

	protected void doValidation()
	{
		if (file == null)
		{
			addError("file", "Please indicate the file you wish to upload");
		}
	}

	protected String doExecute() throws Exception
	{
        if (file.getFileSize() == 0)
        {
            addErrorMessage("Cannot upload a file with 0 bytes");
        }
        else
        {
            GenericValue attachment = getAttachmentManager().createAttachment(getIssue(), getRemoteUser(), file.getFileName(), file.getContentType(), file.getFileSize());

            // create attachment on disk (this doesn't create the attachment entity yet)
            File tempFile = file.getFile();

            File attachmentFile = AttachmentUtils.getAttachmentFile(attachment);
            if (!tempFile.renameTo(attachmentFile))
            {
                addErrorMessage("Could not move attachment from " + tempFile.getAbsolutePath() + " to " + attachmentFile.getAbsolutePath());
            }
        }

		return getRedirect("ManageAttachments.jspa?id=" + getIssue().getLong("id"));
	}

	public void setFile(UploadedFile file)
	{
		log.debug("AttachFile.setFile");
		this.file = file;
	}

    public void setId(Long id)
    {
        log.debug("ID set: " + id);
        super.setId(id);
    }
}
