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.Dao;
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 int 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 (Dao dao = JdbcSource.getDao()) {
			final FooMaster fm = new FooMaster();
			fm.setInsertDatetime(super.getParameter().getDateTime());
			fm.setInsertId("createUserId");
			fm.setFooAddress("fooAddress");
			fm.setFooId("fooId");
			fm.setFooName("fooName");
			fm.setFooPhone("030303030");
			fm.setHooId("hooId");
			fm.setTorokuDatetime(super.getParameter().getDateTime());
			fm.setUpdateDatetime(super.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 int height = 480;
		final int width = 640;
		try (FileInputStream fis = new FileInputStream("./original.jpg")) {
			final BufferedImage image = ImageIO.read(fis);
			final BufferedImage 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";
	}
}
