/*
 * @(#)NntpArticleBody.java
 *
 * Copyright (c) 2001-2002 JScape
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JScape. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JScape.
 */
package com.jscape.inet.nntp;

import java.io.BufferedReader;
import java.io.Serializable;
import java.util.StringTokenizer;


/**
 * Provides methods for constructing and reconstructing Nntp atricle body.
 */
public class NntpArticleBody
        implements Serializable {
    private String body;

    /**
     * Creates new NntpArticleBody instance.
     *
     * @param body the article body
     */
    public NntpArticleBody(String body) {
        this.body = body;
    }

    /**
     * Creates new <code>NntpArticleBody</code> instance from
     * <code>BufferedReader</code>.
     *
     * @param reader the <code>BufferedReader</code> containing body of article
     *
     * @throws NntpException thrown if I/O related error occurs
     * @see NntpException
     */
    public NntpArticleBody(BufferedReader reader)
            throws NntpException {
        StringBuffer buf = new StringBuffer();

        try {
            String line = reader.readLine();

            while (!line.equals(".")) {
                buf.append(line + "\r\n");
                line = reader.readLine();
            }
        } catch (Exception e) {
            throw new NntpException("Could not parse message : " + e.getMessage());
        }

        body = buf.toString();
    }

    /**
     * Gets contents of this <code>NntpArticleBody</code>.
     *
     * @return body
     */
    public String getBody() {
        return body;
    }

    /**
     * Gets body of this NntpArticleBody in format ready  for posting to NNTP
     * server.
     *
     * @return body
     */
    protected String toPostString() {
        if (body == null) {
            return null;
        }

        StringBuffer buf = new StringBuffer();
        StringTokenizer tok = new StringTokenizer(body, "\r\n");

        while (tok.hasMoreElements()) {
            String line = tok.nextToken();

            if (line.charAt(0) == '.') {
                buf.append('.');
            }

            buf.append(line);
            buf.append("\r\n");
        }

        return buf.toString();
    }
}
