package jp.sourceforge.acerola3d.a3viewer;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.net.URL;
import java.util.*;

class A3PHtmlViewer extends WindowAdapter implements ActionListener, HyperlinkListener {
    JDialog dialog;
    JButton backB;
    JEditorPane pane;
    ArrayDeque<URL> rireki = new ArrayDeque<URL>();
    URL dummyURL;
    String firstPageHtml;
    
    A3PHtmlViewer(Frame frame) {
        if (frame==null)
            dialog = new JDialog(frame,"HtmlViewer",false);
        else
            dialog = new JDialog(frame,"HtmlViewer",true);
        dialog.addWindowListener(this);
        dialog.setLayout(new BorderLayout());
        backB = new JButton("もどる");
        backB.addActionListener(this);
        dialog.add(backB,BorderLayout.NORTH);
        pane = new JEditorPane();
        pane.addHyperlinkListener(this);
        pane.setEditable(false);
        pane.setContentType("text/html");
        JScrollPane scrollPane = new JScrollPane(pane);
        dialog.add(scrollPane,BorderLayout.CENTER);
        dialog.setSize(new Dimension(300,300));
        //dialog.setVisible(false);
        try {
            dummyURL = new URL("http://localhost:1234/");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    void open(URL url) {
        rireki.clear();
        rireki.push(url);
        try {
            pane.setPage(url);
        } catch(Exception ee) {
            ee.printStackTrace();
        }
        dialog.setVisible(true);
    }
    void open(String s) {
        firstPageHtml = s;
        rireki.clear();
        rireki.push(dummyURL);
        pane.setText(firstPageHtml);
        dialog.setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource()==backB) {
            if (rireki.size()<=1) {
                dialog.setVisible(false);
                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();
            }
        }
    }
    public void windowClosing(WindowEvent e) {
        dialog.setVisible(false);
    }
}
