/*
 * $Id: RequestUtils.java 394468 2006-04-16 12:16:03Z tmjee $
 *
 * Copyright 2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.k_int.aggregator.dpp.actions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;

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

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.k_int.aggregator.config.DPP_Properties;
import com.k_int.peoples_record.repository.util.ThumbnailStorePathUtil;


public class ThumbnailStreamAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
  private static final long serialVersionUID = 1L;
  private static Log log = LogFactory.getLog(ThumbnailStreamAction.class);
 
  private HttpServletResponse response;
  private HttpServletRequest request;

  private String resource_id;


  public void setServletRequest(HttpServletRequest request) { this.request = request;                 }
  public void setServletResponse(HttpServletResponse response)        { this.response = response;       }
  public void setResourceId(String resource_id)                       { this.resource_id = resource_id; }

  public String execute() throws Exception {
    log.debug("execute");
   
      log.debug("rId: "+resource_id);
      if (resource_id != null && resource_id.length()>0) {

          
          // Get the base directory path for the config that points to the images on disk
          String baseDir = DPP_Properties.getThumbsDirectory();
          String dirPath = ThumbnailStorePathUtil.generateDirectoryPath( Long.parseLong(resource_id), baseDir);
          String filename = resource_id+".jpg";
          log.debug("dirStructure = " + dirPath + " and filename: " + filename);
                       
          // Check to see if the file exists at the path we care about
          // If the image exists stream it back, otherwise return a 404
          File thumbFile = new File(dirPath + filename);
          if ( thumbFile.exists() ) {
              // The file exists on disk - stream it back
              byte[] fileContents = FileUtils.readFileToByteArray(thumbFile);
              
              streamResponse(response, fileContents, "image/jpeg");
          } else {
              // The file doesn't exist - - don't return anything?
          }
          
      }
    return Action.NONE;
  }
  
  
  
  private void streamResponse(HttpServletResponse response, byte[] content, String contentType)
  {
    try
    {
      OutputStream out = response.getOutputStream();
      response.setContentType(contentType);
      ByteArrayInputStream in = new ByteArrayInputStream(content);
      byte[] buffer = new byte[1024];
      int numRead;
      while ((numRead = in.read(buffer)) != -1)
      {
         out.write(buffer, 0, numRead);
      }
      out.flush();
      out.close();
    } catch (Exception e)
    {
      e.printStackTrace();
      this.addActionError("Sorry, downloading of the converted content package failed because of " + e.getMessage());
    }
  }

}
