package project.batch.sample;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.LogManager;

import common.db.JdbcSource;
import common.db.dao.DaoConstraintException;
import project.batch.ProjectBatch;
import project.batch.ProjectPerform;
import project.db.model.FooMaster;

/**
 * バッチサンプル
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class Sample extends ProjectBatch {

	/**
	 * メイン処理
	 *
	 * @param args 引数
	 */
	public static void main(final String... args) {
		final var ret = ProjectPerform.start(Sample.class, args);
		Runtime.getRuntime().exit(ret);
	}

	/**
	 * @see batch.base.Batch#perform(java.lang.String...)
	 */
	@Override
	public int perform(final String... args) {
		LogManager.getLogger().debug("start perform");

		try (var dao = JdbcSource.getDao()) {
			final var fm = new FooMaster();
			fm.setInsertDatetime(getParameter().getDateTime());
			fm.setInsertId("createUserId");
			fm.setFooAddress("fooAddress");
			fm.setFooId("fooId");
			fm.setFooName("fooName");
			fm.setFooPhone("030303030");
			fm.setHooId("hooId");
			fm.setTorokuDatetime(getParameter().getDateTime());
			fm.setUpdateDatetime(getParameter().getDateTime());
			fm.setUpdateId("updateUserId");
			fm.setVersion(1);
			// fm.setId(Long.valueOf(5));
			dao.insert(fm);

			dao.commit();
		} catch (final DaoConstraintException ex) {
			LogManager.getLogger().warn(ex.getMessage());
		}

		// サムネイル
		final var height = 480;
		final var width = 640;
		try (var fis = new FileInputStream("./original.jpg")) {
			final var image = ImageIO.read(fis);
			final var shrinkImage = new BufferedImage(width, height, image.getType());
			shrinkImage.getGraphics().drawImage(image.getScaledInstance(
							width, height, Image.SCALE_AREA_AVERAGING), 0, 0, width, height, null);
			ImageIO.write(shrinkImage, "jpg", new File("./2.jpg"));
		} catch (final IOException ex) {
			LogManager.getLogger().error(ex.getMessage(), ex);
		}

		this.addFile("c:\\temp\\aaa.txt", "AAA");
		this.addFile("c:\\temp\\bbb.txt", "BBB");

		LogManager.getLogger().debug("end perform");

		return RET_SUCCESS;
	}

	/**
	 * @see batch.base.Batch#getBatchName()
	 */
	@Override
	public String getBatchName() {
		return "SAMPLE";
	}
}
