/*******************************************************************************
 * Copyright (c) 2009 IGA Tosiki, NTT DATA BUSINESS BRAINS Corp.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    IGA Tosiki (NTT DATA BUSINESS BRAINS Corp.) - initial API and implementation
 *******************************************************************************/
/*
 * blanco Framework
 * Copyright (C) 2009 NTT DATA BUSINESS BRAINS CORPORATION
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.pdf.page;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import blanco.commons.util.BlancoStringUtil;
import blanco.pdf.BlancoPdfConstants;
import blanco.pdf.page.valueobject.BlancoPdfPageDef;
import blanco.pdf.valueobject.BlancoPdfSetting;

/**
 * ページ定義を扱うためのクラス。
 * 
 * @author Tosiki IGA
 */
public class BlancoPdfPageUtil {
    /**
     * 指定のページを読み込みます。
     * 
     * @param setting
     * @param pageName
     * @return
     */
    public static BlancoPdfPageDef read(final BlancoPdfSetting setting,
            final String pageName) {
        {
            final File dir = new File(setting.getConfPath());
            if (dir.exists() == false) {
                throw new IllegalArgumentException("指定した PDF 設定ファイル・ディレクトリー '"
                        + dir.getAbsolutePath() + "' は存在しませんでした。");
            }
        }
        {
            final File dir = new File(setting.getConfPath() + "/page");
            if (dir.exists() == false) {
                throw new IllegalArgumentException(
                        "指定した PDF 設定ファイル・ディレクトリーの page サブディレクトリー '"
                                + dir.getAbsolutePath() + "' は存在しませんでした。");
            }
        }

        JAXBContext context;
        try {
            context = JAXBContext.newInstance(BlancoPdfPageDef.class);
            final Unmarshaller unmarshaller = context.createUnmarshaller();
            final BlancoPdfPageDef pageDef = (BlancoPdfPageDef) unmarshaller
                    .unmarshal(new File(BlancoStringUtil.null2Blank(setting
                            .getConfPath())
                            + "/page/"
                            + pageName
                            + BlancoPdfConstants.FILEEXT_PDFPAGEDEF));
            return pageDef;
        } catch (JAXBException e) {
            throw new IllegalArgumentException("XMLファイル読み込み時に例外が発生しました。", e);
        }
    }
}
