package edu.school.climate;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Scanner;
import java.awt.event.ActionEvent;

public class ClimateForm extends JFrame {

	/**
	 * Информатика, 8 клас, издателство Просвета, 2017
	 * Автори: Светла Бойчева, Николина Николова, Елиза Стефанова, Антон Денев
	 * Урок 3.4. Условни и циклични конструкции - обобщение
	 * Задача: RxC001 участва в международен проект за об-
	 * мяна на ученици и планира да учи една година в
	 * училище в друга държава. Той вече се е спрял на
	 * няколко атрактивни за него града – Марсилия,
	 * Джакарта, Лима, Монтего Бей, Тампере, Нагоя
	 * и Кейп Таун. За съжаление той трябва много
	 * да се съобразява с климата на съответното
	 * място, тъй като не може да издържа нито на
	 * голяма влага, нито на много ниски или много
	 * високи температури. Според техническите му
	 * характеристики място, на което ще пребива-
	 * ва дълго време, трябва да отговаря на следни-
	 * те условия:
	 * • Минималните месечни температури да не падат под -5 градуса.
	 * • Максималните месечни температури да не са над 30 градуса.
	 * • Средната месечна температурна амплитуда да не е повече от 10 градуса.
	 * • Годишната сума на валежите да не е над 600 mm на квадратен метър.
	 * RxC001 е събрал данни за минималните и макси-
	 * малните месечни температура, както и за ва-
	 * лежите на всяко населено място и ги е запазил
	 * във файлове с имена minTemp.txt. maxTemp.txt
	 * и precipitation.txt, организирани в папки за всеки
	 * град, намиращи се в папка resources.
	 * Създайте приложение с ГПИ, което да помог-
	 * не на RxC001 да избере мястото, на което да
	 * отиде да учи за една година.
	 * 
	 * Версия 1.
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextField txtCity;
	private JTextArea txaResult;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClimateForm frame = new ClimateForm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ClimateForm() {
		Locale.setDefault(new Locale("en", "US"));
		
		
		setTitle("\u041A\u043B\u0438\u043C\u0430\u0442");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setForeground(new Color(51, 102, 102));
		contentPane.setBackground(new Color(255, 255, 204));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new MigLayout("", "[144.00][grow][]", "[][][][][][][grow][][]"));

		JLabel lblCity = new JLabel("\u0413\u0440\u0430\u0434:");
		lblCity.setForeground(new Color(51, 102, 102));
		lblCity.setFont(new Font("Tahoma", Font.BOLD, 12));
		contentPane.add(lblCity, "cell 0 0,alignx trailing");

		txtCity = new JTextField();
		txtCity.setBackground(new Color(255, 255, 153));
		txtCity.setForeground(new Color(51, 102, 102));
		txtCity.setFont(new Font("Tahoma", Font.BOLD, 12));
		contentPane.add(txtCity, "cell 1 0,growx");
		txtCity.setColumns(10);

		JLabel lblMinTempLabel = new JLabel(
				"\u041C\u0438\u043D\u0438\u043C\u0430\u043B\u043D\u0430 \u0442\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u0430: ");
		lblMinTempLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblMinTempLabel, "cell 0 1");

		JLabel lblMinTempValue = new JLabel("");
		lblMinTempValue.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblMinTempValue, "cell 1 1");

		JButton btnMinTemp = new JButton("\u0418\u0437\u0447\u0438\u0441\u043B\u0438");
		btnMinTemp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final String PARENT = "resources/";
				String path = PARENT + txtCity.getText() + "/";
				String filename = path + "minTemp.txt";
				File file = new File(filename);

				try {
					Scanner input = new Scanner(file);

					double minTemp = input.nextDouble();
					double currentTemp;
					while (input.hasNext()) {
						currentTemp = input.nextDouble();
						if (currentTemp < minTemp)
							minTemp = currentTemp;
					}
					input.close();
					
					String res = String.format("%.1f", minTemp);
					lblMinTempValue.setText(res);

				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
			}
		});
		contentPane.add(btnMinTemp, "cell 2 1");

		JLabel lblmaxTempLabel = new JLabel(
				"\u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u043D\u0430 \u0442\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u0430:");
		lblmaxTempLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblmaxTempLabel, "cell 0 2");

		JLabel lblMaxTempValue = new JLabel("");
		lblMaxTempValue.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblMaxTempValue, "cell 1 2");

		JButton btnMaxTemp = new JButton("\u0418\u0437\u0447\u0438\u0441\u043B\u0438");
		btnMaxTemp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final String PARENT = "resources/";
				String path = PARENT + txtCity.getText() + "/";
				String filename = path + "maxTemp.txt";
				File file = new File(filename);

				try {
					Scanner input = new Scanner(file);

					double maxTemp = input.nextDouble();
					double currentTemp;
					while (input.hasNext()) {
						currentTemp = input.nextDouble();
						if (currentTemp > maxTemp)
							maxTemp = currentTemp;
					}
					input.close();
					
					String res = String.format("%.1f", maxTemp);
					lblMaxTempValue.setText(res);

				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		contentPane.add(btnMaxTemp, "cell 2 2");

		JLabel lblTempAmplitudeLabel = new JLabel(
				"\u0421\u0440\u0435\u0434\u043D\u0430 \u0442\u0435\u043C\u043F\u0435\u0440\u0430\u0442\u0443\u0440\u043D\u0430 \u0430\u043C\u043F\u043B\u0438\u0442\u0443\u0434\u0430:");
		lblTempAmplitudeLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblTempAmplitudeLabel, "cell 0 3");

		JLabel lblTemperatureAmplitudeValue = new JLabel("");
		lblTemperatureAmplitudeValue.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblTemperatureAmplitudeValue, "cell 1 3");

		JButton btnTempAmplitude = new JButton("\u0418\u0437\u0447\u0438\u0441\u043B\u0438");
		btnTempAmplitude.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final String PARENT = "resources/";
				String path = PARENT + txtCity.getText() + "/";
				String minTempFilename = path + "minTemp.txt";
				String maxTempFilename = path + "maxTemp.txt";
				File fileMin = new File(minTempFilename);
				File fileMax = new File(maxTempFilename);
				
				try {
					Scanner inputMin = new Scanner(fileMin);
					Scanner inputMax = new Scanner(fileMax);
					
					double sum = 0;
					double min;
					double max;
					for (int i = 1; i <= 12; i++){
						min = inputMin.nextDouble();
						max = inputMax.nextDouble();
						sum += max - min;
					}
					inputMin.close();
					inputMax.close();
					double averageAmplitude = sum / 12;
					String result = String.format("%.2f", averageAmplitude);
					lblTemperatureAmplitudeValue.setText(result);
					
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		contentPane.add(btnTempAmplitude, "cell 2 3");

		JLabel lblPrecipitationSumLabel = new JLabel(
				"\u0413\u043E\u0434\u0438\u0448\u043D\u0430 \u0441\u0443\u043C\u0430 \u043D\u0430 \u0432\u0430\u043B\u0435\u0436\u0438\u0442\u0435");
		lblPrecipitationSumLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblPrecipitationSumLabel, "cell 0 4");

		JLabel lblPrecipitationSumValue = new JLabel("");
		lblPrecipitationSumValue.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblPrecipitationSumValue, "cell 1 4");

		JButton btnPrecipitationSum = new JButton("\u0418\u0437\u0447\u0438\u0441\u043B\u0438");
		btnPrecipitationSum.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final String PARENT = "resources/";
				String path = PARENT + txtCity.getText() + "/";
				String filename = path + "precipitation.txt";
				File file = new File(filename);
				
				try {
					Scanner input = new Scanner(file);
					
					double sum = 0;
					for(int i = 1; i <= 12; i++){
						sum += input.nextDouble();
					}
					input.close();
					
					String result = String.format("%.2f", sum);
					lblPrecipitationSumValue.setText(result);
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		contentPane.add(btnPrecipitationSum, "cell 2 4");

		JLabel lblResult = new JLabel("\u0420\u0435\u0437\u0443\u043B\u0442\u0430\u0442:");
		lblResult.setFont(new Font("Tahoma", Font.PLAIN, 12));
		contentPane.add(lblResult, "cell 0 5");

		txaResult = new JTextArea();
		txaResult.setBackground(new Color(255, 255, 153));
		txaResult.setFont(new Font("Monospaced", Font.PLAIN, 12));
		contentPane.add(txaResult, "cell 0 6 2 2,grow");

		JButton btnCheck = new JButton("\u041F\u0440\u043E\u0432\u0435\u0440\u0438");
		btnCheck.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				double minTemp = Double.parseDouble(lblMinTempValue.getText());
				double maxTemp = Double.parseDouble(lblMaxTempValue.getText());
				double averageAmplitude = Double.parseDouble(lblTemperatureAmplitudeValue.getText());
				double precipitationSum = Double.parseDouble(lblPrecipitationSumValue.getText());
				
				final double MIN_TEMPERATURE_LIMIT = -5;
				final double MAX_TEMPERATURE_LIMIT = 30;
				final double AMPLITUDE_LIMIT = 10;
				final double PRECIPITATION_SUM = 600;
				
				boolean isApropriate = 
						minTemp >= MIN_TEMPERATURE_LIMIT &&
						maxTemp <= MAX_TEMPERATURE_LIMIT &&
						averageAmplitude <= AMPLITUDE_LIMIT &&
						precipitationSum <= PRECIPITATION_SUM;
				if (isApropriate){
					txaResult.setForeground(Color.BLACK);
					txaResult.setText(txtCity.getText() + " е подходящ за теб.");					
				}
				else{
					txaResult.setForeground(Color.RED);
					txaResult.setText(txtCity.getText() + " НЕ е подходящ за теб.");
				}
			}
		});
		contentPane.add(btnCheck, "flowx,cell 0 8");

		JButton btnExit = new JButton("\u0418\u0437\u0445\u043E\u0434");
		btnExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		btnExit.setForeground(new Color(153, 0, 0));
		contentPane.add(btnExit, "cell 2 8,growx");

		JButton btnReset = new JButton("\u0418\u0437\u0447\u0438\u0441\u0442\u0438");
		btnReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				txtCity.setText("");
				lblMaxTempValue.setText("");
				lblMinTempValue.setText("");
				lblPrecipitationSumValue.setText("");
				lblTemperatureAmplitudeValue.setText("");
				txaResult.setText("");
			}
		});
		contentPane.add(btnReset, "cell 0 8");
	}

}
