package xyz.thastertyn.UserInterface.Content;

import java.io.IOException;
import java.util.Optional;

import com.googlecode.lanterna.gui2.Label;
import com.googlecode.lanterna.gui2.Panel;
import com.googlecode.lanterna.gui2.WindowBasedTextGUI;

import xyz.thastertyn.Scrape.JecnaScrape;
import xyz.thastertyn.Types.Choice;
import xyz.thastertyn.UserInterface.Dialogs.OptionsDialog;
import xyz.thastertyn.UserInterface.Listeners.UpdateListener;


/**
 * Wrapper to include all classes that deal with content in some way
 */
public abstract class JecnaContent {
	
	protected Panel mainPanel;
	protected boolean hasStarted = false;
	protected Label borderLabel;
	protected UpdateListener listener;
	protected JecnaScrape scraper;

	/**
	 * Prepares it's content to be display by gettings the panel from {@link #getPanel()}
	 */
	protected abstract void setGUI();

	public JecnaContent(UpdateListener listener)
	{
		this.listener = listener;
	}
	
	/**
	 * Call its scraper class to download content using the provided choice
	 * @param choice
	 * @throws IOException in case download fails in some way
	 */
	protected void download(Choice choice) throws IOException
	{
		if(choice != null)
		{
			scraper.download(choice);
			setGUI();
			mainPanel.setPreferredSize(mainPanel.calculatePreferredSize());
			listener.updatePanel(); 
		}else{
			scraper.download();
			setGUI();
		}
		
		hasStarted = true;
	}

	/**
	 * Tells scraper to download the default content and parse it
	 * @throws IOException
	 */
	public void downloadDefault() throws IOException
	{
		download(null);
	}

	/**
	 * Creates a {@link OptionsDialog} to display its options
	 * @param textGUI where to display the dialog
	 * @throws IOException upon ok, conent is immediatelly downloaded using {@link #download( choice_from_dialog )}
	 */
	public void showOptions(WindowBasedTextGUI textGUI) throws IOException {

		if(scraper.getOptions() == null)
		{
			return;
		}

		OptionsDialog dialog = new OptionsDialog(scraper.getOptions());

		Optional<Choice> choice = dialog.showDialog(textGUI);

		if(choice.isPresent())
		{
			download(choice.get());
		}
	}

	/**
	 * Returns the panel where the content should be held and already arranged for display
	 * @return
	 */
	public Panel getPanel()
	{
		return this.mainPanel;
	}

	/**
	 * Check if something has been downloaded already
	 * @return true or false depending on the download state
	 */
	public boolean hasStarted()
	{
		return this.hasStarted;
	}

	/**
	 * Returns a label with the title text like "Známky", etc.
	 */
	public Label getLabel()
	{
		return this.borderLabel;
	}
}
