package zall.bean;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.FileItem;

import zutil.db.DBConnection;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBeanSQLResultHandler;
import zutil.db.bean.DBBean.*;
import zutil.image.ImageUtil;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;

@DBTable(value="Image", superBean=true)
public class Image extends Media{
	private static final Logger logger = LogUtil.getLogger();	
	public static final String type = "image";
	public static final String IMAGE_FORMAT = "jpg";
	
	@DBLinkTable(table="Comments", beanClass=Comment.class, idColumn="image")
	private LinkedList<Comment> comments;
	
	/**
	 * Loads all the Images from a folder
	 */
	public static List<Image> loadFolder(DBConnection db, Folder folder) throws SQLException{
		if( folder == null || folder.getId() == null )
			return new LinkedList<Image>();
		PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Image WHERE folder=? ORDER BY date DESC");
		sql.setLong(1, folder.getId() );
		return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Image.class, db));
	}
	public static Image load(DBConnection db, long id) throws SQLException{
		return DBBean.load(db, Image.class, id);
	}
		

	public Image(){
		super();
		comments = new LinkedList<Comment>();
	}
	
	public LinkedList<Comment> getComments() {
		return comments;
	}
	public void addComment(Comment cm){
		comments.add( cm );
	}
	
	public void setFile(FileItem item) throws Exception{
		if( folder == null )
			throw new Exception("Folder not set for image!");
		// Generate unique filename
		filename = genFileName( item.getName() );
		filename += "."+FileUtil.getFileExtension( item.getName() );
		File file = folder.getFile( filename, Size.ORIGINAL );
		
		// Move uploaded file
		item.write( file );
	}
	
	/**
	 * Returns the file for the image, and generates an thumbnail if there is no thumbnail
	 * 
	 * @param 		size		is the size of the image
	 */
	public File getFile(Size size) throws IOException{
		if( filename != null ){
			switch( size ){
			case ORIGINAL:
				return folder.getFile( filename, Size.ORIGINAL );
			default:
				File file = folder.getFile( FileUtil.replaceExtension(filename, IMAGE_FORMAT), size );
				File orgFile = folder.getFile( filename, Size.ORIGINAL );
				if( !file.exists() ){
					if(orgFile.exists() && orgFile.canRead() ){
						// Generate new thumbnail
						BufferedImage original = ImageIO.read( orgFile );
						BufferedImage image = null;
						switch( size ){
						case SMALL:
							image = ImageUtil.cropScale(original, 125, 125);
							break;
						case MEDIUM:
							image = ImageUtil.scale(original, 500, 375, true);
							break;
						case LARGE:
							image = ImageUtil.scale(original, 1200, 800, true);
							break;
						default:
							break;
						}
						ImageIO.write(image, IMAGE_FORMAT, file);
					}
					else if( !orgFile.exists() )
						logger.severe("Original image file missing: \""+file.getAbsolutePath()+"\"");
					else if( orgFile.canRead() )
						logger.severe("Can not read original image file: \""+file.getAbsolutePath()+"\"");
				}
				return file;
			}
		}
		return null;
	}
	@Override
	public String getType() {
		return type;
	}
}
