import groovy.net.xmlrpc.*

class ThumbnailController {
	
	CacheService cacheService

	def index = {
			redirect(action: show)
	}
	
	
	
	private synchronized void writeFile(String url, String filepath, String thumbpath) {

		log.warn("Staring download on $url...")

		// def bg = new au.com.bytecode.browser.BrowserGrab();
		// bg.getUrlToFile(url, filepath, thumbpath);
		// bg.shutdown();
		
		
		def server = new XMLRPCServerProxy(grailsApplication.config.thumbnail.serviceurl)

		def list = server.getThumbnail(url)		
		
		FileOutputStream big = new FileOutputStream(filepath)
		big << list[0]
		
		FileOutputStream small = new FileOutputStream(thumbpath)
		small << list[1]

	}
	
	
	private byte[] getFile(String id, boolean writeThumb) {
		
		log.info "id is $id"
		
		BlogEntry entry = BlogEntry.get(id)
		
		def thumbsDir = grailsApplication.config.thumbnail.dir
		
		def thumbnail = "${thumbsDir}/${id}.jpg"
		def filepath = "${thumbsDir}/${id}-orig.jpg"
		
		log.info "file path is $filepath"
		
		if (!(new File(thumbnail).exists())) {
			
			writeFile(entry.link, filepath, thumbnail)
	      
		} else {
			log.info "Already got that image in the cache..."
		}
		  
		
		File file = writeThumb ? new File(thumbnail) : new File(filepath)
		byte[] b = file.readBytes()
		return b
		
	}
	
	private void writeImage(def response, byte[] b) {
		
		response.setContentType("image/jpeg")		 
		response.setContentLength(b.length)
		response.getOutputStream().write(b)
		
	}
	
	def show = { 
			
			def id = params.id
			
	    	// grab thumb bytes from cache if possible
			byte[] b = cacheService.getFromCache("thumbCache", 3600, "small-" + id)
			if (!b) {			
				b = getFile(id, true)
				cacheService.putToCache("thumbCache", 3600, "small-" + id, b)				
			}

			writeImage(response, b)
		
	}
	
	def showLarge = {
		
		def id = params.id
		
    	// grab thumb bytes from cache if possible
		byte[] b = cacheService.getFromCache("thumbCache", 3600, "big-" + id)
		if (!b) {			
			b = getFile(id, false)
			cacheService.putToCache("thumbCache", 3600, "big-" + id, b)				
		}
		
		writeImage(response, b)
		
	}
	
	def preview = {
	
		def url = params.url
		
		def tempThumbsDir = grailsApplication.config.thumbnail.tmpdir
		
		def thumbnail = "${tempThumbsDir}/" + url.encodeAsTempFile() + ".png"
		def filepath = "${tempThumbsDir}/" + url.encodeAsTempFile() + "-orig.png"
		
		def f = new File(thumbnail)
		
		if (!f.exists()) {
			writeFile(url, filepath, thumbnail)
		}
		
		byte[] b = f.readBytes()
		
		writeImage(response, b)
		
	}
	
	
}

