package jp.sourceforge.acerola3d.a3panels;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class HtmlPanel extends JPanel implements ActionListener, HyperlinkListener {
    private static final long serialVersionUID = 1L;
    JButton backB;
    JEditorPane pane;
    ArrayDeque<URL> rireki = new ArrayDeque<URL>();
    URL dummyURL;
    String firstPageHtml;
    
    public HtmlPanel(String urlString) {
        this.setLayout(new BorderLayout());
        backB = new JButton("もどる");
        backB.addActionListener(this);
        this.add(backB,BorderLayout.NORTH);
        pane = new JEditorPane();
        pane.addHyperlinkListener(this);
        pane.setEditable(false);
        pane.setContentType("text/html");
        JScrollPane scrollPane = new JScrollPane(pane);
        //scrollPane.setPreferredSize(new Dimension(100,100));
        this.add(scrollPane,BorderLayout.CENTER);
        try {
            dummyURL = new URL("http://localhost:1234/");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void open(URL url) {
        rireki.clear();
        rireki.push(url);
        try {
            pane.setPage(url);
        } catch(Exception ee) {
            ee.printStackTrace();
        }
    }
    public void open(String s) {
        firstPageHtml = s;
        rireki.clear();
        rireki.push(dummyURL);
        pane.setText(firstPageHtml);
    }
    public void open(File f) {
        try {
            open(f.toURI().toURL());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource()==backB) {
            if (rireki.size()<=1) {
                return;
            }
            rireki.pop();
            URL url = rireki.peekFirst();
            try {
                if (url==dummyURL) {
                    pane.setText(firstPageHtml);
                } else {
                    pane.setPage(url);
                }
            } catch(Exception ee) {
                ee.printStackTrace();
            }
        }
    }
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED){
            try {
              URL url = e.getURL();
              rireki.push(url);
              pane.setPage(url);
            } catch (IOException ee) {
              ee.printStackTrace();
            }
        }
    }
}
