package knahamn;

import java.awt.*;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class GUI extends JFrame{
	private JTabbedPane tabbedPane;
	private JPanel customerPanel;
	private JPanel invoicePanel;
	private JPanel boatPanel;
	private JList<String> tempList;
	private CustomerHandler customerhandler = new CustomerHandler();
	//Customers
	private JTextField firstName;
	private JTextField lastName;
	private JTextField phoneNr;
	private JTextField ssn;
	private JList<String> customerList;
	private JList<String> customerBoatList;
	private JList<String> customerInvoiceList;
	private int currentCustomer = -1;
	
	//Invoices
	private JTextField dateTo;
	private JTextField dateFrom;
	private JTextField sum;
	private JTextField lastPayDay;
	private JTextField boatIdconnector;
	private JTextField ssnConnectorInvoice;
	private JTextField isPayed;
	private JList<String> invoiceList;
	private int currentInvoice = -1;
	//Boats
	private JComboBox boatTypes;
	private JTextField boatLength;
	private JTextField brand;
	private JTextField model;
	private JTextField manufacturingYear;
	private JTextField ssnConnector;
	private JTextField searchField;
	//private JTextField boatId; id can be found in customer
	private JTextField boatSpecificField;
	private JList<String> boatList;
	private int currentBoat = -1;
	
	class WindowEventHandler extends WindowAdapter {
		  public void windowClosing(WindowEvent evt) {
			saveObj();
		    System.exit(0);
		  }
		}
	
	private class ButtonListner implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			String msg = e.getActionCommand();
			switch(msg){
			case "Lägg till kund":
				addCustomer();
				break;
			case "Ändra kund":
				alterCustomer();
				break;
			case "Ta bort kund":
				removeCustomer();
				break;
			case "Lägg till faktura":
				addInvoice();
				break;
			case "Ändra faktura":
				break;
			case "Visa faktura":
				showInvoice();
				break;
			case "Betala faktura":
				payInvoice();
				break;
			case "Lägg till båt":
				addBoat();
				break;
			case "Ändra båt":
				break;
			case "Ta bort båt":
				break;
			case "ladda listor":
				loadLists();
				break;
			case "Sök båt":
				searchBoat();
				break;
			
			}
			
		}
		
	}
	
	public GUI(){
		initiateVariables();
		BuildFrame();
		addComponents();
		readObj();
		addWindowListener(new WindowEventHandler());
	}

	public void searchBoat() {
		int nrOfCustomers = customerhandler.getNrOfCustomers();
		Vector<String> matchingBoats = new Vector<>();
		String[] boats;
		String boatStr;
		boolean containsAllWords = true;
		String[] searchWords = searchField.getText().split(",");
		for(int i = 0; i < nrOfCustomers; i++){
			boats = customerhandler.getCustomer(i).getAllBoatsAsString();
			for(int j = 0; j < boats.length; j++){
				boatStr = boats[j].toString().toLowerCase();
				for(String searchWord : searchWords){
					if(!boatStr.contains(searchWord.toLowerCase())){
						containsAllWords = false;
						
					}
				}
				if(containsAllWords)
					matchingBoats.addElement(boats[j].toString() + " Kundnummer : " + customerhandler.getCustomer(i).getSsn());
				containsAllWords = true;
			}
		}
		this.boatList.setListData(matchingBoats);
	}

	public void payInvoice() {
		currentCustomer = customerList.getSelectedIndex();
		currentInvoice = customerInvoiceList.getSelectedIndex();
		Customer temp = customerhandler.getCustomer(currentCustomer);
		if(temp.getInvoice(currentInvoice).isPayed())
			JOptionPane.showMessageDialog(this, "Fakturan är redan betalad");
		else{
			int answer = JOptionPane.showConfirmDialog(this, "Är du säker på att du vill markera faktura som betald?");
			System.out.println(answer);
			if(answer == 0)
				temp.getInvoice(currentInvoice).setPayed(true);
		}
		
		
	}

	public void showInvoice() {
		String msg = "";
		currentCustomer = customerList.getSelectedIndex();
		currentInvoice = customerInvoiceList.getSelectedIndex();
		Customer temp = customerhandler.getCustomer(currentCustomer);
		String[] strArr = temp.getInvoice(currentInvoice).toString().split(",");
		for(String subMsg : strArr)
			msg += subMsg + "\n";
		JOptionPane.showMessageDialog(this,msg);
	}

	public void saveObj() {
		FileOutputStream fileOut;
		try {
			ObjectOutputStream out;
			fileOut = new FileOutputStream("./temp/customerhandler.ser");
			out = new ObjectOutputStream(fileOut);
			out.writeObject(customerhandler);
			out.close();
			fileOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	public void readObj(){
		 try
	      {
	         FileInputStream fileIn = new FileInputStream("./temp/customerhandler.ser");
	         ObjectInputStream in = new ObjectInputStream(fileIn);
	         customerhandler = (CustomerHandler) in.readObject();
	         in.close();
	         fileIn.close();
	      }catch(IOException i)
	      {
	         i.printStackTrace();
	         return;
	      }catch(ClassNotFoundException c)
	      {
	         System.out.println("CustomerHandler not found");
	         c.printStackTrace();
	         return;
	      }
		 updateCustomerList();
		 updateBoatList();
	}

	public void loadLists() {
		currentCustomer = customerList.getSelectedIndex();
		Customer temp = customerhandler.getCustomer(currentCustomer);
		customerBoatList.setListData(temp.getAllBoatsAsString());
		customerInvoiceList.setListData(temp.getAllInvoicesAsString());
		
		
	}

	public void addBoat() {
		Customer temp = customerhandler.searchCustomer(Integer.parseInt(this.ssnConnector.getText()));
		if(temp == null){
			JOptionPane.showMessageDialog(this, "helt fel kundnummer");
		}
		else if(this.boatTypes.getSelectedItem().equals("Segelbåt")){
			temp.addSailBoat(
				Integer.parseInt(this.boatLength.getText()),
				this.brand.getText(),
				this.model.getText(),
				Integer.parseInt(this.manufacturingYear.getText()),
				Integer.parseInt(this.boatSpecificField.getText())
			);
			updateBoatList();
			clearBoatFields();
		}
		else if(this.boatTypes.getSelectedItem().equals("Motorbåt")){
			temp.addMotorBoat(
				Integer.parseInt(this.boatLength.getText()),
				this.brand.getText(),
				this.model.getText(),
				Integer.parseInt(this.manufacturingYear.getText()),
				Integer.parseInt(this.boatSpecificField.getText())
			);
			updateBoatList();
			clearBoatFields();
		}
		//Uppdatera lite grejor här
		
		
	}

	public void alterCustomer() {
		if(currentCustomer != -1){
			int id;
			try{
				id = Integer.parseInt(this.ssn.getText());
			}
			catch(Exception e){
				id = -1;
			}
			customerhandler.alterCustomer(
					this.firstName.getText(),
					this.lastName.getText(),
					this.phoneNr.getText(),
					id,
					this.currentCustomer
			);
			updateCustomerList();
			clearCustomerTextField();
		}
		
		
	}

	public void removeCustomer() {
		if(currentCustomer > -1){
			customerhandler.remove(currentCustomer);
			updateCustomerList();
			clearCustomerTextField();
			
		}
		
	}
	public void updateCustomerList(){
		currentCustomer = this.customerhandler.getNrOfCustomers() - 1;
		this.customerList.setListData(customerhandler.getAllCustomersAsString());
		this.customerList.setSelectedIndex(currentCustomer);
	}
	public void addInvoice() {
		int customerId;
		int boatPos;
		int nrOfCustomerBoats;
		Customer temp;
		DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		try{
			customerId = Integer.parseInt(this.ssnConnectorInvoice.getText());
			boatPos = Integer.parseInt(this.boatIdconnector.getText());
			temp = this.customerhandler.searchCustomer(customerId);
			if (temp == null){
				JOptionPane.showMessageDialog(this, "Välj giltligt kundnummer");
			}
			else{
				nrOfCustomerBoats = temp.getNrOfBoats();
				if(boatPos >= 0 && nrOfCustomerBoats > boatPos){
					temp.addInvoice(
							formatter.parse(this.dateFrom.getText()),
							formatter.parse(this.dateTo.getText()),
							Double.parseDouble(this.sum.getText()),
							formatter.parse(this.lastPayDay.getText()),
							boatPos
					);
					clearInvoiceFields();
				}	
			}
		}
		catch(ParseException e){
			JOptionPane.showMessageDialog(this, "Fel format på datum");
		}
		catch(NumberFormatException e){
			JOptionPane.showMessageDialog(this, "Kund/Båt - nummer måste vara heltal. \n Summan kan vara heltal eller flyttal");
		}
		catch(Exception e){
			JOptionPane.showMessageDialog(this, "Välj giltligt kund/båt nummer");
		}
		
	}

	private void clearInvoiceFields() {
		this.ssnConnectorInvoice.setText("");
		this.boatIdconnector.setText("");
		this.dateFrom.setText("");
		this.dateTo.setText("");
		this.sum.setText("");
		this.lastPayDay.setText("");
		
	}

	private void updateBoatList() {
		int nrOfBoats = 0;
		Customer temp;
		for(int i = 0; i < this.customerhandler.getNrOfCustomers(); i++){
			temp = this.customerhandler.getCustomer(i);
			nrOfBoats += temp.getNrOfBoats();
		}
		String[] boats = new String[nrOfBoats];
		Vector<String> customerBoats = new Vector<>();
		for(int i = 0; i < this.customerhandler.getNrOfCustomers(); i++){
			temp = this.customerhandler.getCustomer(i);
			for(int j = 0; j < temp.getNrOfBoats(); j++){
				customerBoats.addElement(temp.getBoat(j).toString() + " Kundnummer : " + temp.getSsn());
			}
		}
		for(int i = 0; i< customerBoats.size(); i++)
			boats[i] = customerBoats.elementAt(i);
			
		currentBoat = nrOfBoats - 1;
		this.boatList.setListData(boats);
		this.customerList.setSelectedIndex(currentBoat);
		
	}

	private void clearBoatFields() {
		this.boatLength.setText("");
		this.brand.setText("");
		this.model.setText("");
		this.manufacturingYear.setText("");
		this.boatSpecificField.setText("");
		this.ssnConnector.setText("");
	}

	public void addCustomer() {
		customerhandler.addCustomer(
				this.firstName.getText(),
				this.lastName.getText(),
				this.phoneNr.getText(),
				Integer.parseInt(this.ssn.getText())
		);
		updateCustomerList();
		clearCustomerTextField();
	}

	private void clearCustomerTextField() {
		this.firstName.setText("");
		this.lastName.setText("");
		this.phoneNr.setText("");
		this.ssn.setText("");
		
	}

	private void addComponents() {
		String[] arr = {"Kunder","Fakturor","Båtar"};
		this.customerPanel = buildPanel(arr[0]);
		this.invoicePanel = buildPanel(arr[1]);
		this.boatPanel = buildPanel(arr[2]);
		
		this.customerPanel.add(addCustomerFields());
		this.customerPanel.add(customerList);
		this.customerPanel.add(customerInvoiceList);
		this.customerPanel.add(customerBoatList);
		this.invoicePanel.add(addInvoiceFields());
		this.invoicePanel.add(invoiceList);
		
		this.boatPanel.add(addBoatFields());
		this.boatPanel.add(boatList);
		
		tabbedPane.addTab("Kunder",null,customerPanel,"Kunder i systemet");
		add(tabbedPane);
		tabbedPane.addTab("Fakturor",null,invoicePanel,"Fakturor i systemet");
		add(tabbedPane);
		tabbedPane.addTab("Båtar",null,boatPanel,"Båtar i systemet");
		add(tabbedPane);
		// glöm inte att lägga in lyssnare
	}
//windows listned
//window adapter
	private void BuildFrame() {
		this.setSize(1400,500);
		this.setTitle("Karlskronas HamnSystem");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setResizable(!true);
		
	}
	private JPanel buildButtons(String[] arr){
		ButtonListner bl = new ButtonListner();
		JPanel menuPanel = new JPanel();
		menuPanel.setSize(270,80);
		menuPanel.setLocation(20, 340);
		menuPanel.setLayout(new GridLayout(3,2));
		JButton button = null;
		for(String text: arr){
			button = new JButton(text);
			button.addActionListener(bl);
			menuPanel.add(button);
		}
		return menuPanel;
	}
	private JPanel addCustomerFields(){
		String[] str = {"Lägg till kund", "Ta bort kund","Ändra kund", "ladda listor", "Visa faktura", "Betala faktura"};
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.add(buildButtons(str));
		panel.add(this.firstName);
		panel.add(this.lastName);
		panel.add(this.phoneNr);
		panel.add(this.ssn);
		return panel;
	}
	private JPanel addInvoiceFields(){
		String[] str = {"Lägg till faktura","Ändra faktura","Sök"};
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.add(buildButtons(str));
		panel.add(this.dateFrom);
		panel.add(this.dateTo);
		panel.add(this.sum);
		panel.add(this.lastPayDay);
		panel.add(this.ssnConnectorInvoice);
		panel.add(this.boatIdconnector);
		panel.add(this.isPayed);
		return panel;
	}
	private JPanel addBoatFields(){
		String[] str = {"Lägg till båt","Ändra båt","Ta bort båt","Sök båt"};
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.add(buildButtons(str));
		panel.add(this.ssnConnector);
		panel.add(this.boatTypes);
		panel.add(this.boatLength);
		panel.add(this.brand);
		panel.add(this.model);
		panel.add(this.searchField);
		panel.add(manufacturingYear);
		panel.add(this.boatSpecificField);
		return panel;
	}
	private JPanel buildPanel(String text){
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(1,3));
		panel.setBorder(BorderFactory.createTitledBorder(text));
		return panel;	
	}
	private void initiateVariables() {
		// TODO Auto-generated method stub
		initiateCustomerVariables();
		initateInvoiceVariables();
		initiateBoatVariables();
		this.tabbedPane = new JTabbedPane();
	}
	private void initiateBoatVariables() {
		this.boatTypes = new JComboBox();
		this.boatTypes.addItem("Segelbåt");
		this.boatTypes.addItem("Motorbåt");
		this.boatTypes.setBounds(20, 230, 260, 40);
		this.boatTypes.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = (String) boatTypes.getSelectedItem();
				switch(text){
				case "Motorbåt":
					boatSpecificField.setBorder(BorderFactory.createTitledBorder("Motorkapacitet"));
					break;
				case "Segelbåt":
					boatSpecificField.setBorder(BorderFactory.createTitledBorder("Masthöjd"));
					break;
				}
			}
		});
		
		this.boatLength = new JTextField();
		this.boatLength.setBounds(20, 30, 260, 40);
		this.boatLength.setBorder(BorderFactory.createTitledBorder("Längd"));
		
		this.brand = new JTextField();
		this.brand.setBounds(20, 70, 260, 40);
		this.brand.setBorder(BorderFactory.createTitledBorder("Märke"));
		
		this.model = new JTextField();
		this.model.setBounds(20, 110, 260, 40);
		this.model.setBorder(BorderFactory.createTitledBorder("Modell"));
		
		this.manufacturingYear = new JTextField();
		this.manufacturingYear.setBounds(20, 150, 260, 40);
		this.manufacturingYear.setBorder(BorderFactory.createTitledBorder("Tillverkningsår"));
		
		this.boatSpecificField = new JTextField();
		this.boatSpecificField.setBounds(20, 190, 260, 40);
		this.boatSpecificField.setBorder(BorderFactory.createTitledBorder("Masthöjd"));

		this.ssnConnector = new JTextField();
		this.ssnConnector.setBounds(20,270,260,40);
		this.ssnConnector.setBorder(BorderFactory.createTitledBorder("Kundenummer"));
		
		this.searchField = new JTextField();
		this.searchField.setBounds(290,270,260,40);
		this.searchField.setToolTipText("Separera sökord med ett kommatecken (',')");
		this.searchField.setBorder(BorderFactory.createTitledBorder("sökare!"));
		
		this.boatList = new JList<>();
		this.boatList.setBorder(BorderFactory.createTitledBorder("Alla Båtar"));
	}

	private void initateInvoiceVariables() {
		this.dateTo = new JTextField();
		this.dateTo.setBounds(20, 30, 260, 40);
		this.dateTo.setBorder(BorderFactory.createTitledBorder("Datum till"));
		
		this.dateFrom = new JTextField();
		this.dateFrom.setBounds(20, 70, 260, 40);
		this.dateFrom.setBorder(BorderFactory.createTitledBorder("Datum från"));
		
		this.sum = new JTextField();
		this.sum.setBounds(20, 110, 260, 40);
		this.sum.setBorder(BorderFactory.createTitledBorder("Summa"));
		
		this.lastPayDay = new JTextField();
		this.lastPayDay.setBounds(20, 150, 260, 40);
		this.lastPayDay.setBorder(BorderFactory.createTitledBorder("Sista betalningsdag"));
		
		this.ssnConnectorInvoice = new JTextField();
		this.ssnConnectorInvoice.setBounds(20,190,260,40);
		this.ssnConnectorInvoice.setBorder(BorderFactory.createTitledBorder("Kundnummer"));
		
		this.boatIdconnector = new JTextField();
		this.boatIdconnector.setBounds(20,230,260,40);
		this.boatIdconnector.setBorder(BorderFactory.createTitledBorder("BåtId"));
		
		this.isPayed = new JTextField();
		this.isPayed.setBounds(20,270,260,40);
		this.isPayed.setBorder(BorderFactory.createTitledBorder("Betald"));
		
		this.invoiceList = new JList<>();
		this.invoiceList.setBorder(BorderFactory.createTitledBorder("Alla Fakturor"));
	}

	private void initiateCustomerVariables() {
		this.firstName = new JTextField();
		this.firstName.setBounds(20, 30, 260, 40);
		this.firstName.setBorder(BorderFactory.createTitledBorder("Förnamn"));
		
		this.lastName = new JTextField();
		this.lastName.setBounds(20, 70, 260, 40);
		this.lastName.setBorder(BorderFactory.createTitledBorder("Efternamn"));
		
		this.phoneNr = new JTextField();
		this.phoneNr.setBounds(20,110,260,40);
		this.phoneNr.setBorder(BorderFactory.createTitledBorder("Telefonnummer"));
		
		this.ssn = new JTextField();
		this.ssn.setBounds(20,150,260,40);
		this.ssn.setBorder(BorderFactory.createTitledBorder("Kundnummer"));
		
		this.customerList = new JList<>();
		this.customerList.setBorder(BorderFactory.createTitledBorder("Alla Kunder"));
		
		this.customerBoatList = new JList<>();
		this.customerBoatList.setBorder(BorderFactory.createTitledBorder("Båtar"));
		this.customerInvoiceList = new JList<>();
		this.customerInvoiceList.setBorder(BorderFactory.createTitledBorder("Fakturor"));

		
	}

	public static void main(String[] args) {
		GUI gui = new GUI();
		gui.setVisible(true);
	}
}
