package org.mote.wiimote.whiteboard.calibration;

import java.awt.DisplayMode;
import java.io.IOException;

import org.jdesktop.application.Application;
import org.mote.wiimote.whiteboard.calibration.WiimoteCalibration.CalibrationEvent;
import org.mote.wiimote.whiteboard.calibration.WiimoteCalibration.CalibrationEventListener;

public class CalibrationPersistence implements CalibrationEventListener {
	
	WiimoteCalibration calibration;
	
	public CalibrationPersistence(WiimoteCalibration calibration) {
		this.calibration = calibration;
		calibration.addCalibrationEventListener(this);
	}
	
	public void calibrationEvent(CalibrationEvent e) {
		switch (e) {
			case SCREEN_CHANGED:
				loadCalibrationData();
				break;
			case FINISHED:
				saveCalibrationData();
				break;
		}
	}

	private String calibrationFileName() {
		DisplayMode dm = calibration.getScreen().getDisplayMode();
		return String.format("calibration_%d_%dx%d.txt", calibration.getScreenNumber(), dm.getWidth(), dm.getHeight());
	}
	
	private void loadCalibrationData() {
		try {
			String fileName = calibrationFileName();
			calibration.load(Application.getInstance().getContext().getLocalStorage().openInputFile(fileName));
		} catch (IOException e) {
			// ignore
		}
	}
	
	private void saveCalibrationData() {
		try {
			String fileName = calibrationFileName();
			calibration.save(Application.getInstance().getContext().getLocalStorage().openOutputFile(fileName));
		} catch (IOException e) {
			// ignore
		}
	}

}
