package industries.doublehelix.furrynotemanager.gui;

import java.awt.Desktop;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableModel;

import industries.doublehelix.furrynotemanager.Note;

public class NoteTablePopupMenu extends JPopupMenu implements MouseListener, ActionListener {
	private JMenuItem faItem = new JMenuItem("Open on Furaffinity in Browser");
	private final JTable table;
	private int lastClickRow = -1;
	
	public NoteTablePopupMenu(final JTable table) {
		super();
		this.table = table;
		
		/* since it's apparently not possible to get the row that was clicked on using the normal setComponentPopupMenu
		 * (at least point-conversion from popup to table got me unreal coordinates) we show the popup manually and save
		 * where we showed it. not particularly elegant, but working
		 */
		this.table.addMouseListener(this);
		
		this.faItem.addActionListener(this);
        this.add(faItem);
	}
	
	public void showOnTable(Point where) {
		if (where == null) return;
		int row = this.table.rowAtPoint(where);
		this.lastClickRow = row;
		super.show(this.table, where.x, where.y);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
    	TableModel model = this.table.getModel();
    	if (!(model instanceof NoteTableModel)) return;
		Note note = ((NoteTableModel)model).getNoteAtRow(this.lastClickRow);
		if (note == null) return;
		
		if (e.getSource().equals(this.faItem)) {
			try {
				Desktop.getDesktop().browse(new URI("https://www.furaffinity.net/viewmessage/" + note.getOriginalNoteId() + "/"));
			} catch (IOException | URISyntaxException e1) {
				JOptionPane.showMessageDialog(null, "Could not open browser", "uwu", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (!e.isPopupTrigger()) return;
		if (!e.getSource().equals(this.table)) return;
		NoteTablePopupMenu.this.showOnTable(e.getPoint());
	}

	@Override
	public void mouseClicked(MouseEvent e) {}

	@Override
	public void mouseReleased(MouseEvent e) {}

	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {}
}
