package scheduleGenerator;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.FontUIResource;


/**
 * Class creates ScheduleGeneratorFrame object.
 *

 * @author lamberce.
 *         Created Oct 20, 2012.
 */
public class ScheduleGeneratorFrame extends JFrame implements ActionListener {
	private int numRows = 6;
	private int numCol = 7;
	private String month1;
	private int year1;
	private int day;
	private Config c;
	private String p;
	private String scheduleFileName;
	

	/**
	 * Creates main frame of schedule generator
	 * @param year 
	 * @param month 
	 * @param day 
	 * @param c 
	 * @param date 
	 *
	 */
	public ScheduleGeneratorFrame(int year, int month, int day,Config c){
		this.year1=year;
		this.c=c;
		this.setSize(1500,900);
		ArrayList<JButton> days = new ArrayList<JButton>();
		Calendar x = new GregorianCalendar();
		x.set(year,month,day);
		Calendar cal = Calendar.getInstance();
		int first = 0;
		cal.set(Calendar.DATE, 1);
		cal.set(Calendar.MONTH,month);
		cal.set(Calendar.YEAR, year);
		SimpleDateFormat sdf = new SimpleDateFormat("EEEEEEEEEEEEE");
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("sunday") == 0){
			first = 0;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("monday") == 0){
			first = 1;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("tuesday") == 0){
			first = 2;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("wednesday") == 0){
			first = 3;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("thursday") == 0){
			first = 4;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("friday") == 0){
			first = 5;
		}
		if(sdf.format(cal.getTime()).toLowerCase().compareTo("saturday") == 0){
			first = 6;
		}
		
		if(x.get(Calendar.MONTH)==0){
			this.setTitle("Schedule Generator--January, " + year);
			this.month1 = "Jan";
		}
		if(x.get(Calendar.MONTH)==1){
			this.setTitle("Schedule Generator--February, " + year);
			this.month1 = "Feb";
		}
		if(x.get(Calendar.MONTH)==2){
			this.setTitle("Schedule Generator--March, " + year);
			this.month1 = "Mar";
		}
		if(x.get(Calendar.MONTH)==3){
			this.setTitle("Schedule Generator--April, " + year);
			this.month1 = "Apr";
		}
		if(x.get(Calendar.MONTH)==4){
			this.setTitle("Schedule Generator--May, " + year);
			this.month1 = "May";
		}
		if(x.get(Calendar.MONTH)==5){
			this.setTitle("Schedule Generator--June, " + year);
			this.month1 = "Jun";
		}
		if(x.get(Calendar.MONTH)==6){
			this.setTitle("Schedule Generator--July, " + year);
			this.month1 = "Jul";
		}
		if(x.get(Calendar.MONTH)==7){
			this.setTitle("Schedule Generator--August, " + year);
			this.month1 = "Aug";
		}
		if(x.get(Calendar.MONTH)==8){
			this.setTitle("Schedule Generator--September, " + year);
			this.month1 = "Sep";
		}
		if(x.get(Calendar.MONTH)==9){
			this.setTitle("Schedule Generator--October, " + year);
			this.month1 = "Oct";
		}
		if(x.get(Calendar.MONTH)==10){
			this.setTitle("Schedule Generator--November, " + year);
			this.month1 = "Nov";
		}
		if(x.get(Calendar.MONTH)==11){
			this.setTitle("Schedule Generator--December, " + year);
			this.month1 = "Dec";
		}
		JPanel mainP = new JPanel();
		JPanel menuBar = new JPanel();
			menuBar.setLayout(new GridLayout(1,3));
			menuBar.setPreferredSize(new Dimension(1500,50));
			menuBar.setBackground(Color.BLACK);
		JPanel actionBar = new JPanel();
			actionBar.setLayout(new GridLayout(0,1));
			actionBar.setPreferredSize(new Dimension(125,500));

		JButton print = new JButton("<HTML><font size = 5>Save Printable</font><HTML>");
			print.addActionListener(this);
			print.setBackground(Color.WHITE);

		JButton importer = new JButton("<HTML><font size = 5>Import</font><HTML>");
			importer.addActionListener(this);
			importer.setBackground(Color.WHITE);

//		JButton save = new JButton("<HTML><font size = 5>Save Generated Schedule</font><HTML>");
//			save.addActionListener(this);
//			save.setBackground(Color.WHITE);

		JButton generateRand = new JButton("<HTML><font size = 5>Generate New Schedule</font><HTML>");
			generateRand.addActionListener(this);

		JButton peopleB = new JButton("<HTML><font size = 5>Add People</font><HTML>");
			peopleB.addActionListener(this);

		JButton genMultiMonths = new JButton("<HTML><font size = 5>Generate Schedule for Multiple Months</font><HTML>");
			genMultiMonths.addActionListener(this);

		JButton changeMonth = new JButton("<HTML><font size = 5>Change Month</font><HTML>");
			changeMonth.addActionListener(this);
			

		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());
		mainP.setLayout(new GridLayout(this.numRows+1, this.numCol));		
		
		mainP.add(new JLabel("<HTML><font size = 6>Sunday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Monday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Tuesday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Wednesday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Thursday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Friday</font><HTML>",SwingConstants.CENTER));
		mainP.add(new JLabel("<HTML><font size = 6>Saturday</font><HTML>",SwingConstants.CENTER));

		int y = 0;
		int j =1;
		for(int i = 1; i<(this.numRows*this.numCol)+1; i++){
		String g = Integer.toString(j);
		boolean d = true;
			while(y<first){
				days.add(new JButton(""));
				days.get(i-1).setEnabled(false);
				mainP.add(days.get(i-1));

				y++;
				d = false;
			}
			if((i-first>x.getActualMaximum(Calendar.DAY_OF_MONTH))){
				JButton un = new JButton("");
				un.setEnabled(false);
				mainP.add(un);
			}
			else{
			if(i>first){
			days.add(new JButton(g));
			days.get(i - 1).addActionListener(this);

			days.get(i-1).setFont(new FontUIResource(new Font("Verdana", Font.BOLD, 20)));

			j++;
			}

			if(x.get(Calendar.DAY_OF_MONTH)==(j-1)){
				days.get(i-1).setBackground(Color.RED);
				days.get(i-1).setForeground(Color.WHITE);
			}
			else if(d){
				days.get(i-1).setBackground(Color.LIGHT_GRAY);
			}

			if(d){
				mainP.add(days.get(i - 1));
			}


			}
		}
		

		menuBar.add(print);
		menuBar.add(importer);
//		menuBar.add(save);
		actionBar.add(generateRand);
		actionBar.add(peopleB);
		actionBar.add(genMultiMonths);
		actionBar.add(changeMonth);
		this.add(mainP,BorderLayout.CENTER);
		this.add(menuBar, BorderLayout.NORTH);
		this.add(actionBar, BorderLayout.WEST);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Save Printable</font><HTML>"){
			System.out.println("Place print stuff here");
		}
		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Import</font><HTML>"){
			JFileChooser chooser = new JFileChooser();
			FileNameExtensionFilter filter = new FileNameExtensionFilter(
					"Schedule File", "txt");
			chooser.setFileFilter(filter);
			// this.add(chooser);
			int returnVal = chooser.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				System.out.println("You chose to open this file: "

						+ chooser.getSelectedFile().getName());

			}
			System.out.println("Place import stuff here");
		}



		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Save Generated Schedule</font><HTML>"){
			System.out.println("Place save stuff here");
		}
		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Generate New Schedule</font><HTML>"){
			ScheduleParser a = new ScheduleParser("sampleInput.txt");
			this.scheduleFileName = (String) JOptionPane.showInputDialog(this,
					"Enter the filename for the schedule:\n",
					"Generate new schedule", JOptionPane.PLAIN_MESSAGE, null,
					null, "untitledSchedule.txt");
			if ((this.scheduleFileName == null) || (this.scheduleFileName.length() == 0) || this.scheduleFileName.equals(".txt")
					|| Pattern.compile("[^a-zA-Z0-9 _-]").matcher(this.scheduleFileName).find()) {
				this.scheduleFileName = "untitledSchedule.txt";
			} else if (this.scheduleFileName.length() < 5) {
				this.scheduleFileName += ".txt";
			} else if (!this.scheduleFileName.substring(this.scheduleFileName.length() - 4).equals(".txt")) {
				this.scheduleFileName += ".txt";
			}
			System.out.println(this.scheduleFileName);
			GenerateSchedule genSched = new GenerateSchedule(a.parseSchedule(),this.c,1,this.scheduleFileName,this.month1);
			genSched.run();
		}
		

		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Add People</font><HTML>"){
			PeopleFramework peop = new PeopleFramework();
			peop.setVisible(true);
		}
		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Generate Schedule for Multiple Months</font><HTML>"){
			ScheduleParser a = new ScheduleParser("sampleInput.txt");
			this.scheduleFileName = (String) JOptionPane.showInputDialog(this,
					"Enter the filename for the schedule:\n",
					"Generate new schedule", JOptionPane.PLAIN_MESSAGE, null,
					null, "untitledSchedule.txt");
			if ((this.scheduleFileName == null) || (this.scheduleFileName.length() == 0) || this.scheduleFileName.equals(".txt")
					|| Pattern.compile("[^a-zA-Z0-9 _-]").matcher(this.scheduleFileName).find()) {
				this.scheduleFileName = "untitledSchedule.txt";
			} else if (this.scheduleFileName.length() < 5) {
				this.scheduleFileName += ".txt";
			} else if (!this.scheduleFileName.substring(this.scheduleFileName.length() - 4).equals(".txt")) {
				this.scheduleFileName += ".txt";
			}
			System.out.println(this.scheduleFileName);
			String m = (String) JOptionPane.showInputDialog(this, "Enter number of months to generate: \n", "Generate new schedule", JOptionPane.PLAIN_MESSAGE, null, null, "");
			GenerateSchedule genSched = new GenerateSchedule(a.parseSchedule(),this.c,Integer.parseInt(m),this.scheduleFileName,this.month1);
			genSched.run();
		}
//			System.out.println("Place Gen multi month stuff here");
		
		else if(((JButton) e.getSource()).getText().toString() == "<HTML><font size = 5>Change Month</font><HTML>"){
			int monthNum=0;
			int year = 0;
			boolean isTrue = false;
			this.dispose();
			while(!isTrue){

				String month = JOptionPane.showInputDialog("Type in the name of the month you would like to view:");

				String inYear = JOptionPane.showInputDialog("In what year would you like to view this month:");
					year = Integer.parseInt(inYear);
				System.out.println(month.toLowerCase());
				if(month.toLowerCase().compareTo("january")==0){
					monthNum = 0;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("february")==0){
					monthNum = 1;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("march")==0){
					monthNum = 2;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("april")==0){
					monthNum = 3;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("may")==0){
					monthNum = 4;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("june")==0){
					monthNum = 5;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("july")==0){
					monthNum = 6;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("august")==0){
					monthNum = 7;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("september")==0){
					monthNum = 8;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("october")==0){
					monthNum = 9;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("november")==0){
					monthNum = 10;
					isTrue = true;
				}
				else if(month.toLowerCase().compareTo("december")==0){
					monthNum = 11;
					isTrue = true;
				}
			}
			ScheduleGeneratorFrame j = new ScheduleGeneratorFrame(year,monthNum,1,this.c);


			j.setVisible(true);
		}
		else{
			JFrame a = new JFrame(this.month1 + " " + ((JButton) e.getSource()).getText().toString());
			a.setSize(300,500);
			a.setLayout(new GridLayout(2,1));
			final JTextArea b = new JTextArea();
			Dimension label = new Dimension(500,300);
			b.setPreferredSize(label);
			JButton save = new JButton(new AbstractAction("Save") {

				@Override
				public void actionPerformed(ActionEvent e) {
					System.out.println("This is the internal save button");
					ArrayList<String> holdTop = new ArrayList<String>();
					ArrayList<String> holdBottom = new ArrayList<String>();
					String temp = "";
					Scanner y = null;
					
					try {
						y = new Scanner(new File(ScheduleGeneratorFrame.this.scheduleFileName));
					} catch (FileNotFoundException exception) {
						exception.printStackTrace();
					}
					if(y.hasNextLine()){
						temp = y.nextLine();
					}
					System.out.println(temp);
					while(y.hasNextLine()&&!(temp.equals("+" + month1 + " " + day + ", " + year1))){
						holdTop.add(temp);
						temp = y.nextLine();
					}
					boolean m = true;
					while(((!temp.substring(0,1).equals("+"))||(m))&&y.hasNextLine()){
						temp = y.nextLine();
						m = false;
					}

					while(y.hasNextLine()){
						holdBottom.add(temp);
						temp = y.nextLine();
					}
					holdBottom.add(temp);
					
					try {
						PrintStream x = new PrintStream(new File(ScheduleGeneratorFrame.this.scheduleFileName));
						for(int i = 0; i<holdTop.size();i++){
							x.println(holdTop.get(i));
						}
						x.println(b.getText());
						for(int i = 0; i<holdBottom.size();i++){
							x.println(holdBottom.get(i));
						}
						x.close();
					} catch (FileNotFoundException exception) {
						exception.printStackTrace();
					}
				}
			});
			

			Scanner y;
			try {
				y = new Scanner(new File(ScheduleGeneratorFrame.this.scheduleFileName));
			
			this.p = "";

			String adder;
			String stopper1 = ((JButton) e.getSource()).getText().toString();

			int c = 0;
			day = Integer.parseInt(((JButton) e.getSource()).getText().toString());
			int stopper2 = Integer.parseInt(stopper1)+1;
			boolean stop = false;
			boolean k = true;
			while(y.hasNextLine()){
				adder = y.nextLine() + " ";
				if(adder.equals("+" + this.month1 + " " + ((JButton) e.getSource()).getText().toString() + ", " + this.year1 + " ")) {

					while((!adder.substring(0,1).equals("+"))&&y.hasNextLine()||k){
						k = false;
						p += adder + "\n";
						adder = y.nextLine() + " ";
					}
					if(!y.hasNextLine()){
						p+= adder;
					}
					stop = true;
				}
				if(stop){
					break;
				}
			}
			} catch (FileNotFoundException exception) {
				exception.printStackTrace();
			}
			b.setText(p);
			a.add(save);
			a.add(b);
			a.setVisible(true);
			a.add(save);
		}
	}
}
