package oracle.fodemo.share.imageloader.service;
/* $Id: ImageLoaderServiceAMImpl.java /main/1 2009/07/25 16:53:55 tfisher Exp $ */

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.InputStream;
import java.io.OutputStream;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import java.sql.SQLException;

import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.BlobDomain;
import oracle.jbo.domain.DBSequence;
import oracle.jbo.domain.Timestamp;
import oracle.jbo.domain.Number;
import oracle.jbo.server.ApplicationModuleImpl;
import oracle.jbo.server.ViewObjectImpl;
// ---------------------------------------------------------------------
// ---    File generated by Oracle ADF Business Components Design Time.
// ---    Custom code may be added to this class.
// ---    Warning: Do not modify method signatures of generated methods.
// ---------------------------------------------------------------------
public class ImageLoaderServiceAMImpl extends ApplicationModuleImpl {
    /**This is the default constructor (do not remove).
     */
    public ImageLoaderServiceAMImpl() {
    }

    /**Container's getter for ProductImages.
     */
    public ViewObjectImpl getProductImages() {
        return (ViewObjectImpl)findViewObject("ProductImages");
    }

    /**
     * This method loops through all of the files within the specified and 
     * creates a row in the product images table for each. The product that the 
     * image is associated with is deduced from the file name as this is a simple
     * data load with a known set of data
     * @param imageDirectory
     * @throws IOException
     * @throws SQLException
     */

     public void loadImages(String imageDirectory) throws IOException,
                                                              SQLException {
             final String thumbnailDir = "/thumbnails";
            
             //Full sized images
             loadImageSubset(imageDirectory,null);
//             loadImageSubset(null);

             //now the Thumbnails
             loadImageSubset(imageDirectory,thumbnailDir);
//             loadImageSubset(thumbnailDir);
      
         }
    
    public void loadImageSubset(String imageDirectory, String subDirectory) throws IOException, 
                                                         SQLException {
        final String imageExt = ".jpg";
        File imageDir = null;        
        boolean loadingThumbnails = (subDirectory!=null);
        
        URL imagesUrl = null;
        if (loadingThumbnails){
       imagesUrl = getClass().getClassLoader().getResource(imageDirectory + subDirectory);
//        imagesUrl = new URL("file:///C:\\FOD\\Trunk\\4_6_09\\Infrastructure\\DBSchema\\Images\\thumbnails\\");
        }
        else {
        imagesUrl = getClass().getClassLoader().getResource(imageDirectory);
//            imagesUrl = new URL("file:///C:\\FOD\\Trunk\\4_6_09\\Infrastructure\\DBSchema\\Images\\");
        }
        // Translate to URI to get rid of spaces
        URI imagesUri = null;
        try {
            imagesUri = new URI(imagesUrl.toString());
        } catch (URISyntaxException e) {
        }   
            imageDir =new File(imagesUri);
            System.out.println("Loading " + (loadingThumbnails?"thumbnails": "images") + " from: " + imageDir);
        if (imageDir.isDirectory()) {
                    File[] children = imageDir.listFiles();
                    //Ignore non-jpg files
                    for (int i = 0; i < children.length; i++) {
                        String fullFileName = children[i].toString();
                        String productIdFileName = children[i].getName();
                        int fileExtensionStart = productIdFileName.indexOf(imageExt);
                        if (fileExtensionStart != -1) {
                            String imageId = productIdFileName.replace(imageExt,"");
                            Number imageIdNum = new Number(Integer.parseInt(imageId));
                            Row row = getProductImages().createRow();
                            BlobDomain imgDomain = new BlobDomain();
                            OutputStream blobOutputStream;
                            // Open the sample file as a stream for insertion into the Blob column
                            blobOutputStream = imgDomain.getBinaryOutputStream();
                            File imgFile = new File(fullFileName);
                            InputStream sampleFileStream;
         
                            // Buffer to hold chunks of data to being written to the Blob.
                            sampleFileStream = new FileInputStream(imgFile);
                            byte[] buffer = new byte[10 * 1024];
         
                            // Read a chunk of data from the sample file input stream,
                            // and write the chunk to the Blob column output stream.
                            // Repeat until file has been fully read.
                            int nread = 0; // Number of bytes read
                            while ((nread = sampleFileStream.read(buffer)) != -1)
                                blobOutputStream.write(buffer, 0,
                                                       nread); // Write to Blob
         
                            // Close both streams
                            sampleFileStream.close();
                            blobOutputStream.close();
                            //ProductImageId set by db sequence
                            row.setAttribute(1, imageIdNum);
                            row.setAttribute(2, loadingThumbnails?"Y":"N");
                            if (loadingThumbnails) {
                                // Resolve the ImageId of the full sized image
                                Number detailImageId = findDetailImageByProductId(imageIdNum);
                                row.setAttribute(3, detailImageId);
                            }
                            row.setAttribute(4, imgDomain);
                            getDBTransaction().commit();
                        }
                    }
                } else {
                    System.out.println(imageDir + " is not a valid images directory");
                }   
            }
    

    public Number findDetailImageByProductId(Number imageIdNum){
        // Create a programmatic where clause to find the PRODUCT_IMAGE_ID for the supplied PRODUCT_ID
        ViewObject productImages = getProductImages();
        productImages.defineNamedWhereClauseParam("paramProductId", null, null);
        productImages.setWhereClause("PRODUCT_ID = :paramProductId");
        productImages.setNamedWhereClauseParam("paramProductId", imageIdNum);
        productImages.executeQuery();
        Row product = productImages.first();
        DBSequence detailImageId = (DBSequence)product.getAttribute("ProductImageId");
        
        //Reset the where clause
        productImages.setWhereClause(null);
        productImages.removeNamedWhereClauseParam("paramProductId");
        
        //Return the detail image id for the new record
        return detailImageId.getSequenceNumber();
   }
}

