package xyz.thastertyn.ContentDisplay;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.UnknownHostException;

import javax.security.auth.login.CredentialException;

import com.googlecode.lanterna.gui2.WindowBasedTextGUI;
import com.googlecode.lanterna.gui2.dialogs.MessageDialog;
import com.googlecode.lanterna.gui2.dialogs.MessageDialogButton;

import xyz.thastertyn.Tuples.Triplet;

public class LoginController {
	
	private xyz.thastertyn.JecnaParse.Login login = new xyz.thastertyn.JecnaParse.Login();
	private xyz.thastertyn.ContentDisplay.CredentialsInput dialog = new CredentialsInput();

	private WindowBasedTextGUI textGUI = null;

	public LoginController(WindowBasedTextGUI textGUI)
	{
		this.textGUI = textGUI;
	}

	public void login()
	{
		if(checkForCredentials()) // Credentials exist
		{
			if(loginUsingCredentials()) // They are accessible and can read them
			{
				return;
			}
		}

		try
		{
			Triplet<String, String, Boolean> data = dialog.showDialog(textGUI); // Failed to get credentials to log in, get them from user
			login.loginJecna(data.getValue0(), data.getValue1());
		} catch (UnknownHostException e) {
			MessageDialog.showMessageDialog(textGUI, "No Internet connection",
					"There seems to be no internet connection, reverting to cached data", 
					MessageDialogButton.OK);
			return;
		} catch (CredentialException e)
		{
			MessageDialog.showMessageDialog(textGUI, "Incorrect username or password", 
			"The username or password you entered is incorrect", 
			MessageDialogButton.OK);
			return;
		} catch (IOException e)
		{
			MessageDialog.showMessageDialog(textGUI, "There was an error", 
			"Maybe try again and it will go away", 
			MessageDialogButton.Retry);
			return;
		}
	}

	/**
	 * Zkontroluje zda jiz neexistuji ulozene udaje na systemu
	 * @return <ul>
	 * <li> {@code true} soubor existuje a neni prazdny </li>
	 * <li> {@code false} neexistuje, nebo je prazdny </li>
	 * </ul>
	 */
	private boolean checkForCredentials()
	{
		return false;
		//File credentials = null;

		//if(System.getProperty("os.name").equals("Linux"))
		//{
		//	credentials = new File("~/.local/share/jecnak/credentials.json");

		//}else if(System.getProperty("os.name").contains("Windows"))
		//{
		//	credentials = new File(System.getenv("APPDATA\\jecnak\\"));
		//}

		//if(!credentials.exists() || credentials.length() == 0)
		//{
		//	return false;
		//}
		//return true;
	}

	public boolean saveCredentials(String user, String pass)
	{
		File credentials;

		if(System.getProperty("os.name").equals("Linux"))
		{
			credentials = new File("~/.local/share/jecnak/credentials.json");

		}else if(System.getProperty("os.name").contains("Windows"))
		{
			credentials = new File(System.getenv("APPDATA\\jecnak\\"));
		}else{
			return false;
		}

		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(credentials));
			writer.append("username=" + user);
			writer.append("password=" + pass);

			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private boolean loginUsingCredentials()
	{
		File credentials;

		if(System.getProperty("os.name").equals("Linux"))
		{
			credentials = new File("~/.local/share/jecnak/credentials.json");

		}else if(System.getProperty("os.name").contains("Windows"))
		{
			credentials = new File(System.getenv("APPDATA\\jecnak\\"));
		}else{
			return false;
		}

		if(!credentials.exists() || credentials.length() == 0) 
		{
			return false;
		}

		String user = "";
		String pass = "";

		try {
			BufferedReader reader = new BufferedReader(new FileReader(credentials));

			String line = "";
			while((line = reader.readLine()) != null)
			{
				if(line.matches("^[a-z]\\=.*$"))
				{
					String key = line.split("=")[0];
					String value = line.split("=")[1];
					
					switch(key)
					{
						case "username":
							user = value;
							break;
						case "password":
							pass = value;
							break;
						default:
							continue;
					}
				}else{
					continue;
				}
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		try {
			login.loginJecna(user, pass);
		} catch (CredentialException | IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}
}
