package hyperscout2.applet;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Window;
import java.net.URL;

import scone.ras.Connection;


class PopupWindow extends Window {

    int lineCount = 0;   // Count lines starting with 0
    int linePos = 1;   // Position of first popup line
    int width = 0;
    int height = 0;
    public PopupLine lines[] = new PopupLine[30];   // array with popup-lines
    public Image images[] = new Image[30];       // array with images of popup
    public boolean doCache = false;  // Default: Don't cache pages.

    PopupLine active = null;
    PopupLine over = null;
    Image offscreen;
    Dimension offscreensize;
    Graphics offgraphics;
    DisplayApplet applet = null;

    final static Color bgColor = new Color(255, 255, 255);  // 242,238,210);   // bright yellow
    final static Color borderColor = new Color(128, 128, 128);  // 136,130,120);   // brown
    final static String server = "localhost";              // Connect to ras-server on local proxy...
    final static int port = 8084;                     // Port number of RAS-Server
    final static String generator = "hyperscout2.LinkDataGenerator"; // Connect to ras-server on local proxy...

    final static String wbiPort = "8088";
    final static String resPath = "/_hyperscout2/resources/";

    /**
     * Create new popup window object
     */
    PopupWindow(DisplayApplet applet, String linkId) {
        super(new java.awt.Frame());
        setBackground(bgColor);
        this.applet = applet;

        setFont(new Font("SansSerif", Font.PLAIN, 11));
        buildPopup(linkId, applet.getGraphics().getFontMetrics(new Font("SansSerif", Font.PLAIN, 11)));
    }

    /**
     * Read data from ras-Server and paint the contents of the popup-window.
     */
    void buildPopup(String linkId, FontMetrics fm) {

        try {
            Connection con = new Connection(server, port, generator, false);

            System.out.println("Connetion created: " + con);
            con.wake();                    // Necessary to send!
            System.out.println("Link:" + linkId);
            con.write(linkId);            // Ask for Hyperscout information to link
            System.out.println("Linkid written!");

            // read data from generator
            String line = "";

            while (!line.equals("--begin")) {
                line = con.read();
            }           // read empty lines...
            System.out.println(line);     // beginning found

            line = con.read();              // Do we want to cache this info?
            if (line.equals("cache")) {
                doCache = true;
            }                // Cache popup!

            while (!line.equals("--end"))  // read until end
            {
                line = con.read();
                if (line.equals("--line")) {
                    String l1 = con.read(); // image
                    String l2 = con.read(); // title
                    String l3 = con.read(); // text
                    String l4 = con.read(); // bgColor

                    if (l1.equals("--end") || l2.equals("--end")
                            || l3.equals("--end") || l4.equals("--end")) {
                        break;
                    }

                    Image image = applet.getImage(new URL("http://" + server + ":" + wbiPort + resPath + l1));

                    prepareImage(image, this);
                    PopupLine pl = new PopupLine(image, l2, l3, l4, 400, fm);

                    addLine(pl);
                }
            }

            con.close();  // is closed when window is hidden...
        } catch (Exception exc) {
            try {
                Image image = applet.getImage(new URL("http://" + server + ":" + wbiPort + resPath + "flash.gif"));
                PopupLine error = new PopupLine(image, "Error", exc.toString(), "FF8080", 400, fm);

                addLine(error);
            } catch (Exception exec) {
                System.err.println("Error sending error message");
                exec.printStackTrace();
            }
            exc.printStackTrace();
        }
    }

    /**
     * find a line with a specific label
     */
    int findLine(String label) {
        for (int i = 0; i < lineCount; i++) {
            if (lines[i].getTitle().equals(label)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * set minimal size of popupwindow
     */
    public void setMinSize() {
        width = 0;    // Reset size.
        height = 0;
        Rectangle b = null;

        for (int i = 0; i < lineCount; i++) {
            b = lines[i].getBounds();
            if (b.x + b.width > width) {
                width = b.x + b.width;
            }
            if (b.y + b.height > height) {
                height = b.y + b.height;
            }
        }
        // System.out.println(DisplayApplet.browser+" "+DisplayApplet.version);
        if (DisplayApplet.browser.indexOf("Netscape") >= 0) {
            resize(width + 1, height + 1);
        }  // Netscape shows only the window without warning ;-)
        else if (DisplayApplet.browser.indexOf("Sun Microsystems") >= 0) {
            resize(width + 1, height + 22);
        } // Extra Space for Sun's Java Plugin
        else {
            // resize(width + 1, height + 18);
            resize(width + 1, height + 18);
        } // Extra Space: The Internet Explorer also displays a warning message.
    }

    /**
     * get the height of the popup
     */
    public int getHeight() {
        return height + 2;
    }

    /**
     * get the width of the popup
     */
    public int getWidth() {
        return width + 2;
    }

    /**
     * add line to popup window
     */
    private void addLine(PopupLine line) {
        line.setParent(this);
        line.setLocation(1, linePos);
        Rectangle b = line.getBounds();

        linePos += b.height + 0;    // Calculate pos of nex line, one line space...
        lines[lineCount] = line;
        lineCount++;
    }

    /**
     * Male die Grafik...
     */
    public void paint(Graphics g) {
        update(g);
    }

    /**
     * Paint graphics
     */
    public synchronized void update(Graphics g) {
        Dimension d = getSize();

        if ((offscreen == null) || (d.width != offscreensize.width)
                || (d.height != offscreensize.height)) {
            offscreen = createImage(d.width, d.height);
            offscreensize = d;
            if (offgraphics != null) {
                offgraphics.dispose();
            }
            offgraphics = offscreen.getGraphics();
            offgraphics.setFont(getFont());
        }

        // Paint Background
        offgraphics.setColor(getBackground());
        offgraphics.fillRect(0, 0, d.width, d.height);

        // Paint bounding box
        offgraphics.setColor(borderColor);
        if (DisplayApplet.browser.indexOf("Netscape") >= 0) {
            offgraphics.drawRect(0, 0, d.width - 1, d.height - 1);
        } else {
            offgraphics.drawRect(0, 0, d.width - 1, d.height - 18);
        }

        // Paint boxes
        for (int i = 0; i < lineCount; i++) {
            lines[i].paint(offgraphics);
        }
        g.drawImage(offscreen, 0, 0, null);
    }

    public PopupLine findLine(int x, int y) {
        for (int i = 0; i < lineCount; i++) {
            if (lines[i].contains(x, y)) {
                return lines[i];
            }
        }
        return null;
    }

    public boolean doCache() {
        return doCache;
    }

    public void hide() {
        super.hide();
    }

}

