package exceptionhandling.v1;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.NonWritableChannelException;
import java.util.Scanner;

public class Driver {

	public static void main(String[] args) throws IOException {
		System.out.println("*** VERSION 1 ***");
		lockFile();
		String filename = chooseFile();
		System.out.println("Does " + filename + " contain a holiday message? " + 
		                    HolidayFinder.holiday(filename));
	}
	
	private static String chooseFile() {
		System.out.println("Pick your file\n1. docs/greeting.txt\n2. docs/misnamed.txt\n3. docs/locked.txt\n4. docs/missing.txt");
		Scanner sc = new Scanner(System.in);
		String filename = "";
		String answer = sc.nextLine();
		switch (answer) {
		case "1" : filename = "docs/greeting"; break;
		case "2" : filename = "docs/misnamed"; break;
		case "3" : filename = "docs/locked"; break;
		case "4" : filename = "docs/missing"; break;
		}
		sc.close();
		return filename + ".txt";
	}
	 
	private static void lockFile() {
		String file = "docs/locked.txt";
		try {
		    @SuppressWarnings("resource")  // We do NOT want to close this to preserve lock
			FileOutputStream out = new FileOutputStream(file);
			out.getChannel().lock();
		    out.write(-1);
		}
		catch (NonWritableChannelException e) {
		}
		catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
}
