package inc.monsters.mias.backing;

import inc.monsters.mias.data.Kid;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.faces.context.FacesContext;

import org.apache.myfaces.trinidad.component.UIXInput;
import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.event.ReturnEvent;
import org.apache.myfaces.trinidad.model.UploadedFile;

public class EditKidForm {
	private static Logger log = Logger.getLogger("inc.monsters.mias");
	private static final String IMAGE_DIRECTORY = "/usr/share/photos/";

	private UIXInput bravenessInput;
	private UploadedFile photoFile;

	public UIXInput getBravenessInput() {
		return bravenessInput;
	}

	public void setBravenessInput(UIXInput bravenessInput) {
		this.bravenessInput = bravenessInput;
	}

	public String save() {
		doApply();
		return "ok";
	}

	public String apply() {
		doApply();
		return "apply";
	}

	private void doApply() {
		savePhoto();
	}

	public void bravenessCalcReturn(ReturnEvent returnEvent) {
		log.fine("bravenessCalcReturn() called");
		if (returnEvent.getReturnValue() != null) {
			log.fine("   returnValue = " + returnEvent.getReturnValue());
			getBravenessInput().setSubmittedValue(null);
			getBravenessInput().setValue((Double) returnEvent.getReturnValue());
		}
	}

	public UploadedFile getPhotoFile() {
		log.fine("getPhotoFile()");
		return photoFile;
	}

	public void setPhotoFile(UploadedFile file) {
		log.fine("setPhotoFile(" + file + ")");
		this.photoFile = file;
	}

	private void savePhoto() {
		log.fine("savePhoto()");
		UploadedFile photoFile = getPhotoFile();
		RequestContext requestContext = RequestContext.getCurrentInstance();
	    Kid selectedKid = (Kid)requestContext.getPageFlowScope().get("selectedKid");
		log.fine("photoFile = " + photoFile);
		if (photoFile != null) {
			selectedKid.setPhoto(photoFile.getFilename());
			// Make sure the image directory exists
			// TODO: use same image directory setting as for PhotoServlet
			File f = new File(IMAGE_DIRECTORY);
			if (!f.exists()) {
				f.mkdir();
			}
			f = new File(IMAGE_DIRECTORY + photoFile.getFilename());
			if(f.exists()) {
				f.delete();
			}
			log.fine("savePhoto(): file = " + f.getAbsolutePath());
			
			FileOutputStream fos = null;
			InputStream is = null;
			try {
				fos = new FileOutputStream(f);
				log.fine("savePhoto() : output stream constructed");

				is = photoFile.getInputStream();
				byte[] buffer = new byte[4096];
				int totalBytes = 0;
				for (int n; (n = is.read(buffer)) != -1;) {
					totalBytes += n;
					fos.write(buffer, 0, n);
				}

				log.fine("savePhoto() : " + totalBytes + " bytes written");
				fos.close();
			} catch (FileNotFoundException e) {
				log.fine("savePhoto() : FileNotFoundException");
				e.printStackTrace();
			} catch (IOException e) {
				log.fine("savePhoto() : IOException");
				e.printStackTrace();
			} finally {
				try {
					fos.close();
				} catch (IOException e) {
				} finally {
					try {
						is.close();
					} catch (IOException e) {
					}
				} 
			}
		}
	}

	public String getPhotoUrl() {
		log.fine("getPhotoUrl()");
		RequestContext requestContext = RequestContext.getCurrentInstance();
	    Kid selectedKid = (Kid)requestContext.getPageFlowScope().get("selectedKid");
		String photoFileName = selectedKid.getPhoto();
		log.fine("getPhotoUrl(): photoFileName = " + photoFileName);
		if (photoFileName != null) {
			photoFileName = "/photos/" + photoFileName;
		} else {
			photoFileName = "";
		}
		log.fine("getPhotoUrl(): photoFileName = " + photoFileName);
		return photoFileName;
	}

}
