package project.web.job;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;

import batch.status.Job;
import batch.status.JobFile;
import online.struts.action.UniForm;

/**
 * JobFileダウンロードアクション
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class JobFileAction implements DownloadJobFile {

	/**
	 * @see project.web.job.DownloadJobFile
	 * #canDownload(online.struts.action.UniForm, batch.status.Job)
	 */
	@Override
	public boolean canDownload(final UniForm model, final Job js) {
		return true;
	}

	/**
	 * ファイルダウンロード処理
	 *
	 * @param job ジョブ情報
	 * @param finfo ダウンロードファイル情報
	 * @param request HttpServletRequestオブジェクト
	 * @param response HttpServletResponseオブジェクト
	 */
	@Override
	public void fileDownload(final Job job, final JobFile finfo,
			final HttpServletRequest request, final HttpServletResponse response) {

		try (var is = new FileInputStream(getFile(finfo))) {
			try (var os = response.getOutputStream()) {
				// 複写
				int cnt;
				final var buffer = new byte[4096];
				while (0 < (cnt = is.read(buffer))) {
					try {
						os.write(buffer, 0, cnt);
					} catch (final IOException ex) {
						LogManager.getLogger().info(ex.getMessage());
						return;
					}
				}
				os.flush();
			} catch (final IOException ex) {
				LogManager.getLogger().error(ex.getMessage(), ex);
			}

		} catch (final URISyntaxException | IOException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}

		try {
			if (!response.isCommitted()) {
				response.reset();
				response.resetBuffer();
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				response.flushBuffer();
			}
		} catch (final IOException e) {
			LogManager.getLogger().info(e.getMessage());
		}
	}

	/**
	 * File取得
	 * @param finfo ダウンロードファイル情報
	 * @return File
	 * @throws URISyntaxException URIシンタックス例外
	 */
	private File getFile(final JobFile finfo) throws URISyntaxException {
		return new File(new URI(finfo.getPathName() + "/" + finfo.getFileName()).getPath());
	}
}
