package org.j69.eewiki.wiki.tag;

import java.nio.charset.CharacterCodingException;

import org.apache.oro.text.perl.Perl5Util;

import org.j69.eewiki.util.CacheConfig;
import org.j69.eewiki.util.WebUtil;
import org.j69.eewiki.wiki.transformer.DataTag;

/**
 * ImageDataTag
 * usage : #Image(filename) -> <img src="images/filename">
 * @version $Revision: 1.3 $ $Date: 2003/06/30 17:07:44 $
 */
public class ImageDataTag implements DataTag {

    // コンフィグ
    private final static CacheConfig config_ = CacheConfig.getInstance( );

    private static final String REGULAR_EXPRESSION =
        "s!#Image\\(([^)]*)\\)!<img src=\\\""+ config_.getConfig("define.dir.upload") + "/$1\\\">!g";

    /**
     * @see jp.mobster.webapp.wiki.transform.DataTag#get()
     */
    public String get(String pageData) {
        Perl5Util perl = new Perl5Util();
        StringBuffer sb = new StringBuffer();
        final String[] datas = pageData.split("\n");

        for (int i = 0; i < datas.length; i++) {
            String tmp = datas[i];
            if (perl.match("m!^#Image.+!", tmp)) {
                //オプションの取得
                String filename = "";
                if (perl.match("m!.+\\(.+\\)!", tmp)) {
                    filename = perl.substitute("s!.+\\((.+)\\)!$1!g", tmp);
                    //拡張子
                    String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                    try {
                        //エンコードしたファイル名の取得
                        filename = WebUtil.getEncodeFileName(filename) + "." + suffix;
                    } catch (CharacterCodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                tmp = "#Image(" + filename + ")";
            }
            sb.append(tmp + "\n");
        }
        pageData = sb.toString();
        return perl.substitute(REGULAR_EXPRESSION, pageData);
    }

}
