/*
 * Copyright 2007 Kickmogu Co. Ltd. All rights reserved.
 *
 * 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.
 */



/*
 * 作成日: 2006/11/15
 *
 */
package com.kickmogu.rhythm.mail;

import com.kickmogu.*;
import com.kickmogu.rhythm.core.SessionManager;
import com.kickmogu.rhythm.core.Member;
import com.kickmogu.rhythm.core.dao.MemberDao;
import com.kickmogu.rhythm.mail.ws.*;
import com.kickmogu.s2.S2Util;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Category;
import javax.mail.*;

public class FileDownloader extends HttpServlet {
	static Category log = Category.getInstance(FileDownloader.class.getName());

	static public String getFileName(Part part)
			throws javax.mail.MessagingException {
		String fname = Util.toStr(part.getFileName());
		if (!fname.equals(""))
			return fname;
		String desc = Util.toStr(part.getDescription());
		String ctype = Util.toStr(part.getContentType());
		if (ctype.indexOf("/") >= 0)
			ctype = ctype.substring(ctype.indexOf("/") + 1);
		return desc + "." + ctype;
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		
		Folder folder = null;
		try {
			MailWs mailWs = new MailWs();
			String folderName = req.getParameter("folder");
			int msgNo = Integer.parseInt(req.getParameter("msgNo"));
			int partNo = Integer.parseInt(req.getParameter("partNo"));
			int mailSettingId = Integer.parseInt(req.getParameter("mailSettingId"));
			
			String sessionId = req.getParameter("sessionId");
			int memId = Integer.parseInt(req.getParameter("memId"));
			// セッションの有効性を確認
			if (!SessionManager.isValidSession(sessionId, memId)) {
				log.info("Upload File session timeout:" + memId + "," + sessionId);
				return;
			}

			MemberDao memdao = (MemberDao) S2Util.getS2Container().getComponent(MemberDao.class);
			Member loginMember = memdao.getMember(memId);
			folder = mailWs.getTargetFolder(loginMember, mailSettingId, folderName);
			folder.open(Folder.READ_ONLY);
			Message[] msg = folder.getMessages(msgNo, msgNo);
			Multipart part = (Multipart) msg[0].getContent();
			BodyPart body = part.getBodyPart(partNo);
			res.setContentType("application/kikmogu-stream");
			String fname = mailWs.getAttachFilename(getFileName(body));
			res.setHeader("Content-Disposition", "inline; filename=\""
			 	+ new String(fname.getBytes("Shift_JIS"), "8859_1") + "\"");
			InputStream in = body.getInputStream();
			OutputStream out = res.getOutputStream();
			byte[] buf = new byte[512];
			int read_sz;
			while ((read_sz = in.read(buf)) > 0)
				out.write(buf, 0, read_sz);
			in.close();
			out.close();
		} catch (Exception e) {
			log.error(e);
		} finally {
			if (folder != null && folder.isOpen()) {
				try {
					folder.close(false);
				} catch (MessagingException e) {
					log.error(e);
				}
			}
		}

	}
}
