/*******************************************************************************
 * 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.font;

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.font.valueobject.BlancoPdfFontDef;
import blanco.pdf.valueobject.BlancoPdfSetting;

import com.lowagie.text.pdf.BaseFont;

/**
 * フォントを扱うためのクラス。
 * 
 * @author Tosiki IGA
 */
public class BlancoPdfFontUtil {
    /**
     * 指定のフォントを読み込みます。
     * 
     * @param setting
     * @param fontName
     * @return
     */
    public static BlancoPdfFontDef read(final BlancoPdfSetting setting,
            final String fontName) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(BlancoPdfFontDef.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            final BlancoPdfFontDef fontDef = (BlancoPdfFontDef) unmarshaller
                    .unmarshal(new File(BlancoStringUtil.null2Blank(setting
                            .getConfPath())
                            + "/font/" + fontName + ".xml"));
            return fontDef;
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("XMLファイル読み込み時に例外が発生しました。", e);
        }
    }

    public static BaseFont getFont(final BlancoPdfSetting setting,
            final String fontName) {
        final BlancoPdfFontDef fontDef = read(setting, fontName);
        try {
            // TODO 現在は非埋め込みを選択。
            return BaseFont.createFont(fontDef.getFontName(), fontDef
                    .getFontEncoding(), BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            throw new IllegalArgumentException("フォントの作成に失敗", e);
        }
    }
}
