/**
 * For source:
 
 * https://github.com/berlinbrown/physicsforprogrammers/tree/master/projects/MathServices
 
 * Also see:
 
 * https://github.com/berlinbrown
 * http://berlinbrown.github.com/
 * http://berlinbrown.github.com/applets.html
 */
package org.berlin.chem.gae.web;

/*
 * Pngj PNG writer used with Google App Engine.
 
 * From pngj:
 * http://code.google.com/p/pngj/ 
 */

import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.Stack;
import java.util.Vector;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.berlin.chem.gae.DBModelSquirmReaction;
import org.berlin.chem.gae.DBSquirm;
import org.berlin.chem.gae.DBSquirmCell;
import org.berlin.chem.gae.DBSquirmChemistry;
import org.berlin.chem.gae.dao.ArtificialChemistryStateDAO;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Text;

/**
 * Basic math utilities for google app engine.
 
 @author bbrown (berlin.brown at gmail.com)
 *
 */
public class ArtificialChemistryImageServlet extends HttpServlet {
   
  /**
   * Serial version id. 
   */
  private static final long serialVersionUID = 1L;
  
  public void doGet(final HttpServletRequest request, final HttpServletResponse responsethrows IOException {  
    doPost(request, response);
  // End of the class //
  
  public void doPost(final HttpServletRequest request, final HttpServletResponse responsethrows IOException {        
    response.setContentType("image/png");              
    final OutputStream os = response.getOutputStream();
    final ArtificialChemistryStateDAO dao = new ArtificialChemistryStateDAO();    
    long t1 = System.currentTimeMillis();    
    final Stack<String> recordDatabase = new Stack<String>();    
    Text dataForStack = null;
    for (final Entity ee : dao.list()) {
        dataForStack = (Text)ee.getProperty("chemlog");
        break;
    }
    if (dataForStack != null) {
        recordDatabase.push(dataForStack.getValue());
        // End of the if //        
    final Vector<DBSquirmCell> cellListDatabase = new Vector<DBSquirmCell>();        
    final Vector<DBModelSquirmReaction> reactionDatabase = new Vector<DBModelSquirmReaction>();                                                       
    final DBSquirmChemistry chemistry = new DBSquirmChemistry(reactionDatabase);
    final DBSquirm squirmFrame = new DBSquirm(cellListDatabase, recordDatabase);                             
    squirmFrame.initSquirmChem(chemistry, 5);
    squirmFrame.step(chemistry, 30);
    squirmFrame.render(os);    
    final Random random = new Random();
    if (!recordDatabase.isEmpty()) {
        if (random.nextDouble() 0.10) {
            dao.log(request.getRemoteAddr(), recordDatabase.peek());
        }
    // End of the if //    
  // End of the class //  
// End of the class //