/*
 * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
 *
 * This file is part of Resin(R) Open Source
 *
 * Each copy or derived work must preserve the copyright notice and this
 * notice unmodified.
 *
 * Resin Open Source is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Resin Open Source is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
 * of NON-INFRINGEMENT.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Resin Open Source; if not, write to the
 *   Free Software Foundation, Inc.
 *   59 Temple Place, Suite 330
 *   Boston, MA 02111-1307  USA
 *
 * @author Scott Ferguson
 */

package com.caucho.amber.field;

import java.io.IOException;

import java.util.ArrayList;

import java.util.logging.Logger;
import java.util.logging.Level;

import com.caucho.bytecode.JMethod;

import com.caucho.util.L10N;

import com.caucho.log.Log;

import com.caucho.config.ConfigException;

import com.caucho.java.JavaWriter;

import com.caucho.amber.type.EntityType;

import com.caucho.amber.table.Column;

/**
 * Represents a map to entities.
 */
public class EntityMapField extends AbstractField {
  private static final L10N L = new L10N(EntityMapField.class);
  protected static final Logger log = Log.open(EntityMapField.class);

  private ArrayList<Column> _indexColumns;
  private JMethod _mapMethod;

  private EntityType _targetType;

  private IdField _id;
  private IdField _index;
  
  public EntityMapField(EntityType entityType)
  {
    super(entityType);
  }

  /**
   * Sets the field name.
   */
  public void setName(String name)
  {
    // hack for EJB maps
    try {
      super.setName(name);
    } catch (ConfigException e) {
      log.log(Level.FINEST, e.toString(), e);
    }
    
    setJavaType(java.util.Map.class);
  }

  /**
   * Sets the target type.
   */
  public void setTargetType(EntityType type)
  {
    _targetType = type;
  }

  /**
   * Returns true if the methods are abstract.
   */
  public boolean isUpdateable()
  {
    return false;
  }

  /**
   * Sets the map method.
   */
  public void setMapMethod(JMethod method)
  {
    _mapMethod = method;
  }

  /**
   * Sets the id field.
   */
  public void setId(IdField id)
  {
    _id = id;
  }

  /**
   * Sets the index field.
   */
  public void setIndex(IdField index)
  {
    _index = index;
  }

  /**
   * Sets the index columns.
   */
  public void setIndexColumns(ArrayList<Column> columns)
  {
    _indexColumns = columns;
  }

  /**
   * Sets the index columns.
   */
  public ArrayList<Column> getIndexColumns()
  {
    return _indexColumns;
  }

  /**
   * Generates loading cache
   */
  public void generateUpdate(JavaWriter out, String mask, String pstmt,
			     String index)
    throws IOException
  {
  }

  /**
   * Generates loading cache
   */
  public void generateLoadFromObject(JavaWriter out, String obj)
    throws IOException
  {
  }

  /**
   * Generates loading cache
   */
  public void generateUpdateFromObject(JavaWriter out, String obj)
    throws IOException
  {
  }
  
  /**
   * Generates the select clause.
   */
  public String generateLoadSelect(String id)
  {
    return null;
  }

  /**
   * Updates the cached copy.
   */
  public void generateCopyUpdateObject(JavaWriter out,
				       String dst, String src,
				       int updateIndex)
    throws IOException
  {
  }

  /**
   * Updates the cached copy.
   */
  public void generateCopyLoadObject(JavaWriter out,
				       String dst, String src,
				       int loadIndex)
    throws IOException
  {
  }

  /**
   * Generates the get property.
   */
  public void generateSuperGetter(JavaWriter out)
    throws IOException
  {
  }

  /**
   * Generates the get property.
   */
  public void generateSuperSetter(JavaWriter out)
    throws IOException
  {
  }

  /**
   * Generates the set property.
   */
  public void generateGetProperty(JavaWriter out)
    throws IOException
  {
    if (getGetterMethod() != null) {
      out.println();
      out.println("public " + getJavaTypeName() + " " + getGetterName() + "()");
      out.println("{");
      out.pushDepth();

      out.println("return null;");
    
      out.popDepth();
      out.println("}");
    }
    
    if (_mapMethod != null) {
      out.println();
      out.print("public ");
      out.print(_mapMethod.getReturnType().getPrintName());
      out.print(" " + _mapMethod.getName() + "(");
      out.print(_mapMethod.getParameterTypes()[0].getPrintName());
      out.println(" a0)");
      out.println("{");
      out.pushDepth();

      out.println("if (__caucho_session == null)");
      out.println("  return null;");
      out.println();


      out.println("try {");
      out.pushDepth();
      
      out.println("com.caucho.amber.AmberQuery query;");

      EntityType targetType = _targetType;
      
      String table = targetType.getName();

      out.print("String sql = \"SELECT o");
      out.print(" FROM " + table + " o");
      out.print(" WHERE ");

      EntityType sourceType = getSourceType();
      ArrayList<IdField> keys = sourceType.getId().getKeys();

      out.print("o." + _index.getName() + "=?1");

      for (int i = 0; i < keys.size(); i++) {
	IdField key = keys.get(i);
	
	out.print(" and ");

	out.print("o." + _id.getName() + "." + key.getName() + "=?" + (i + 2));
      }

      out.println("\";");
      
      out.println("query = __caucho_session.prepareQuery(sql);");

      out.println("int index = 1;");
      _index.getType().generateSet(out, "query", "index", "a0");
      
      for (int i = 0; i < keys.size(); i++) {
	IdField key = keys.get(i);

	key.generateSet(out, "query", "index", "this");
      }
      
      out.print("return (");
      out.print(_mapMethod.getReturnType().getPrintName());
      out.println(") query.getSingleResult();");

      out.popDepth();
      out.println("} catch (Exception e) {");
      out.println("  throw com.caucho.amber.AmberRuntimeException.create(e);");
      out.println("}");
    
      out.popDepth();
      out.println("}");
    }
  }
}
