/*
 * Copyright (c) 2008 Keith A. Jaska
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package geriatricassistant.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.osgi.service.log.LogService;

import com.buglabs.bug.base.pub.ITimeProvider;
import com.buglabs.bug.module.camera.pub.ICameraDevice;

/**
 * The Class CameraRecorder. The class, which extends Thread, uses the Camera to
 * take an image every 30 seconds and store it in a directory, with today's date
 * as the name (yyyMMdd), and a file with the current time as the name (HHmmss).
 * 
 * @author Keith A. Jaska
 */
public class CameraRecorder extends Thread {
	private ITimeProvider timeProvider;
	private ICameraDevice cameraDevice;
	private LogService logService;

	public CameraRecorder(ITimeProvider timeProvider,
			ICameraDevice cameraDevice, LogService logService) {
		this.timeProvider = timeProvider;
		this.cameraDevice = cameraDevice;
		this.logService = logService;
	}

	public void run() {
		while (true) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat();
				sdf.applyPattern("yyyyMMdd");
				String directory = sdf.format(timeProvider.getTime())
						+ File.separator;
				File file = new File(directory);
				if (!file.exists()) {
					file.mkdirs();
				}
				sdf.applyPattern("HHmmss");
				String filename = sdf.format(timeProvider.getTime()) + ".jpg";
				logService.log(LogService.LOG_INFO,
						"Camera image stored here: " + filename);
				FileOutputStream fos = new FileOutputStream(directory
						+ filename);
				fos.write(cameraDevice.getImage());
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				// This essentially schedules the camera to take a picture in 30
				// seconds.
				sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}
}