/*
 * blancoDb
 * Copyright (C) 2004-2005 Yasuo Nakanishi
 * 
 * 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.db.expander.query;

import blanco.db.expander.implementor.BlancoDbImplementor;
import blanco.db.properties.GenerationProperties;
import blanco.db.util.BlancoDbObjectStorage;
import blanco.db.util.BlancoDbQueryParserUtil;
import blanco.ig.expander.Type;
import blanco.ig.expander.implementor.StringLiteral;
import blanco.ig.expander.method.MethodExpander;

/**
 * @author Yasuo Nakanishi
 */
public class GetQueryMethod extends MethodExpander {
    private String _query = "";

    private GenerationProperties _properties = null;

    public GetQueryMethod(String query) {
        super("getQuery");
        _query = query;
        _properties = BlancoDbObjectStorage.getInstance()
                .getGenerationProperties();
    }

    public void setupSignature() {
        // getQueryはpublicに変更。
        setReturnType(new Type(String.class));

        if (_properties.isGenerateJavaDoc()) {
            getJavaDoc().addLine("クエリの取得メソッド<br>");
            getJavaDoc().addLine("実際に実行するSQL文を戻します。");
            getJavaDoc().addReturn("実際に実行されるSQL文");
        }
    }

    public void implement() {
        BlancoDbImplementor implementor = new BlancoDbImplementor(getData());

        // 2005.04.15 t.iga 改行は改行として出力するように変更。
        String escapedQuery = _query.replaceAll("\"", "\\\\\"").replaceAll(
                "\n", "\\\\n");

        // TODO: クエリの #パラメータの?への変換は適切に処理すべきです。現在は仮で旧バージョンを利用。
        String actualSql = new BlancoDbQueryParserUtil(escapedQuery)
                .getNaturalSqlString();

        implementor.addReturn(new StringLiteral(actualSql));
    }
}