/*
 * @(#)ImapMessage.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.imap;

import com.jscape.inet.email.EmailMessage;

import java.io.Serializable;
import java.util.Locale;

/**
 * Represents an email message retrieved from an IMAP server containing additional information
 * such as message flags and message id.
 */
public class ImapMessage
        implements Serializable {

    private EmailMessage message;
    private String flags = null;
    private int id;

    /**
     * Constructs a new ImapMessage instance
     *
     * @param message the message
     * @param id      the message id
     * @param flags   the message flags response from IMAP server in response to FETCH id FLAGS command
     */
    public ImapMessage(EmailMessage message, int id, String flags) {
        this.message = message;
        this.id = id;
        if (flags != null) {
            this.flags = flags.toLowerCase(Locale.ENGLISH);
        }
    }

    /**
     * Gets if message has been seen (read).
     *
     * @return true if seen (read), false otherwise
     */
    public boolean isSeen() {
        return check("\\seen");
    }

    /**
     * Gets if message is recent.
     *
     * @return true if recent, false otherwise
     */
    public boolean isRecent() {
        return check("\\recent");
    }

    /**
     * Gets if message is in a draft.
     *
     * @return true if draft, false otherwise
     */
    public boolean isDraft() {
        return check("\\draft");
    }

    /**
     * Gets if message is deleted
     *
     * @return true if deleted, false otherwise
     */
    public boolean isDeleted() {
        return check("\\deleted");
    }

    /**
     * Gets if message has been answered.
     *
     * @return true if answered, false otherwise
     */
    public boolean isAnswered() {
        return check("\\answered");
    }

    /**
     * Gets email message for this message
     *
     * @return an EmailMessage instance
     *
     * @see EmailMessage
     */
    public EmailMessage getMessage() {
        return message;
    }

    /**
     * Gets current message id
     *
     * @return the message id
     */
    public int getId() {
        return id;
    }

    /**
     * Checks for existence of flag
     *
     * @param flag the flag to check for
     *
     * @return true if flag exists, false otherwise
     */
    private boolean check(String flag) {
        if (flags == null) {
            return false;
        } else {
            return flags.indexOf(flag) != -1;
        }
    }
}
