/*
    Reads "news" from text file with headlines and URLs.
    Vertical scroll.

    Parameters (see also WebBase):
        DATAFILE        File (relative to the HTML document) to get news from
            def: fresh.txt
        CLICKCOLOR      Color of "clickable" text
            def: blue
        HEADCOLOR       Color of headline text
            def: red
        FONT            Font to use (Arial,Courier,Dialog,TimesRoman)
            def: Dialog
        FONTSIZE        Size (in pts.) of message font
            def: 12

    Copyright 1998 by E. A. Graham, Jr.
    Free to use or modify.
 */

import java.awt.*;
import java.applet.*;
import java.util.*;
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;

public class NewsTxt extends WebBase {
    // the incremental scrolling distance in pixels
    private final int DEFAULT_SCROLL = 10;
    int     scrollUnit;

    // fonts for the headline and message (headline is bold version of message)
    Font    fontHeadline,fontMessage;

    // the various colors
    Color   clickColor,headColor;

    // the current "top" message
    int     msgTop;

    // The File and the Messages
    String  fileName = null;
    Vector  vMessages = new Vector();

    int     gap = 15;           // gap between messages - tweak if necessary

    //************************************************************************
    // initialization time!
    //************************************************************************
    public void init() {
        super.init();

        //********************************************************************
        // get the HTML parameters or set to defaults
        //********************************************************************
        String  sp;

        sp = ReadText("SCROLLBY");
        scrollUnit = (sp != null) ? Integer.parseInt(sp) : DEFAULT_SCROLL;
//        sp = ReadText("UPDATETIME");
//        updateTime = (sp != null) ? Integer.parseInt(sp) : 0;
        sp = ReadText("DATAFILE");
        fileName = (sp == null) ? "fresh.txt" : sp;
        clickColor = ReadColor("CLICKCOLOR",Color.blue);
        headColor = ReadColor("HEADCOLOR",Color.red);

        //********************************************************************
        // get the HTML font parameters and set them up
        //********************************************************************
        sp = ReadText("FONTSIZE");
        int fs = (sp != null) ? Integer.parseInt(sp) : 12;
        sp = ReadText("FONT");
        if (sp==null) sp = "Dialog";
        fontMessage = new Font(sp,Font.PLAIN,fs);
        fontHeadline = new Font(sp,Font.BOLD,fs);

        msgTop = 0;
        updateNews();
    }

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

    // draw the stuff
    public synchronized void update(Graphics g) {
        if(loaded) {
            super.update(g);

            // loop over the loaded news items...
            for (Enumeration e = vMessages.elements() ; e.hasMoreElements() ;) {
                ((NewsMessage)e.nextElement()).draw(appGC,borderWidth,headColor,foreColor,clickColor);
            }

            //...next comes the border...
            drawBorder(maxWidth,maxHeight,borderWidth);

            //...fade the edges
            g.drawImage(appImage, 0, 0, this);
        }
    }

    public boolean handleEvent(Event event) {
        return super.handleEvent(event);
    }

    // handle any clicks, okay?
    public boolean mouseDown(Event ev,int x, int y) {
        for (Enumeration e = vMessages.elements() ; e.hasMoreElements() ;) {
            URL clicked = ((NewsMessage)e.nextElement()).click(y);
            if (clicked != null) {
                getAppletContext().showDocument(clicked,"_top");
                break;
            }
        }
        return true;
    }

    // scroll all the messages
    synchronized void doAppThing() {
        int     maxM = vMessages.size(),
                lastBottom;
        NewsMessage m;
        boolean reset = false;

        // update the positions of the messages
        if (maxM==0) return;
        // has the top message gone off?
        m = (NewsMessage)vMessages.elementAt(msgTop);
        if (m.bottom() + scrollUnit + gap <= 0) msgTop++;
        if (msgTop >= maxM) {
            msgTop = 0;
            lastBottom = maxHeight;
            for (Enumeration e = vMessages.elements() ; e.hasMoreElements() ;) {
                m = (NewsMessage)e.nextElement();
                m.resetTop(lastBottom);
                lastBottom = m.bottom() + gap;
            }
        }

        // scroll the visible messages
        for (int x = msgTop; x < maxM; x++) {
            m = (NewsMessage)vMessages.elementAt(x);
            m.move(scrollUnit);
        }
    }

    // (re)read the news file
    synchronized void updateNews() {
        InputStream         conn;
        DataInputStream     dis = null;
        URL     theURL = null;

        if (fileName==null) return;
        try {
            if (fileName.indexOf("http://") >= 0 ) {
                theURL = new URL(fileName);
            }
            else {
                theURL = new URL(getDocumentBase(),fileName);
            }
            try {
                int     mode = 0,
                        lastbottom = maxHeight;
                NewsMessage m = null;
                String  line;

                conn = theURL.openStream();
                dis = new DataInputStream(new BufferedInputStream(conn));
                while( (line=dis.readLine())!=null) {
                    if (line.startsWith("#") || line.length()==0) continue;
                    if (line.substring(0,4).equalsIgnoreCase("@END")) {
                        if (m!=null) {
                            lastbottom = m.bottom() + gap;
                            vMessages.addElement(m);
                        }
                        mode = 0;
                        continue;
                    }
                    if (line.substring(0,4).equalsIgnoreCase("@URL") && m!=null) {
                        m.addLink(getDocumentBase(),line.substring(4));
                        continue;
                    }
                    switch (mode) {
                        case 0:
                            if (line.substring(0,5).equalsIgnoreCase("@HEAD")) {
                                mode = 1;
                                m = new NewsMessage(lastbottom,maxWidth-(2*borderWidth),appGC,fontHeadline,fontMessage);
                                m.addHeadLine(line.substring(5));
                            }
                            break;
                        case 1:
                            if (line.substring(0,4).equalsIgnoreCase("@MSG")) {
                                mode = 2;
                                m.addMessageLine(line.substring(4));
                            }
                            else {
                                m.addHeadLine(line);
                            }
                            break;
                        default:
                            m.addMessageLine(line);
                            break;
                    }
                }
            }
            catch (IOException e) {}

        }
        catch (MalformedURLException e) {}
    }
}

class NewsMessage {
    int     top,height,
            currentY,
            maxWidth = 0;

    URL     link;

    // the first element in each of these is the font, the second is the font metrics
    Vector  message = null;
    Vector  headline = null;

    NewsMessage (int startat,int mw,Graphics g,Font fontHead,Font fontMessage) {
        FontMetrics fm;

        height = 0;
        top = startat;

        headline = new Vector();
        headline.addElement(fontHead);
        fm = g.getFontMetrics(fontHead);
        headline.addElement(fm);

        message = new Vector();
        message.addElement(fontMessage);
        fm = g.getFontMetrics(fontMessage);
        message.addElement(fm);

        maxWidth = mw - 10;
    }

    public void draw (Graphics g,int bw,Color headColor,Color msgColor,Color urlColor) {
        // is this thing even in the picture?
        if (top+height <= 0) return;

        // set up and do the headline
        // then do the message
        currentY = top;
        drawline(g,headline,bw,headColor);
        drawline(g,message,bw,((link==null) ? msgColor : urlColor));
    }

    public void move(int amount) { top -= amount; }
    public void resetTop(int startat) { top = startat; }
    public int bottom() { return top+height; }

    public void addLink(URL docbase,String s) {
        try {
            if (s.indexOf("http://") >= 0 ) {
                link = new URL(s);
            }
            else {
                link = new URL(docbase,s);
            }
        }
        catch (MalformedURLException e) {};

    }

    public void addHeadLine(String s) {
        addLine(headline,s);
    }
    public void addMessageLine(String s) {
        addLine(message,s);
    }

    // calcuate where the lines will wrap and update the height of the message
    void addLine(Vector v,String line) {
        try {
            FontMetrics fm = (FontMetrics)v.elementAt(1);
            String      s,t;
            int         x,y,
                        h;

            h = fm.getHeight();
            if (v.size() > 2) {
                 s = new String ((String)v.lastElement() + " " + line);
                 v.removeElementAt(v.size()-1);
                 height -= h;
            }
            else {
                s = line;
            }

            for (x=0; s.length() > 0; x=y+1) {
                y = s.indexOf(' ',x);
                if (y== -1) {
                    if ((fm.stringWidth(s) > maxWidth) && x>0) {
                        v.addElement(s.substring(0,x));
                        s = s.substring(x);
                        height += h;
                    }
                    v.addElement(s);
                    height += h;
                    s = "";
                }
                else {
                    t = s.substring(0,y);
                    if (fm.stringWidth(t) > maxWidth) {
                        v.addElement(s.substring(0,x));
                        s = s.substring(x);
                        y = -1;
                        height += h;
                    }
                }
            }
        }
        catch (NoSuchElementException e) {}
    }

    // draw the indicated lines
    void drawline(Graphics g,Vector v,int bw,Color c) {
        try {
            FontMetrics fm = (FontMetrics)v.elementAt(1);
            int         h,i,y;

            h = fm.getHeight();
            y = fm.getAscent();     // distance to baseline

            g.setColor(c);
            g.setFont((Font)v.firstElement());
            for (i=2; i<v.size(); i++) {
                String s = (String)v.elementAt(i);
                g.drawString(s,bw+5,currentY+y);
                currentY += h;
            }
        }
        catch (NoSuchElementException e) {}
    }

    // see if this is clickable and in the right range
    public URL click(int y) {
        if (y>=top && y<=top+height) return(link);
        return(null);
    }
}
