/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2004-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

package ipipan.poliqarp.connection;

/**
 * A synchronous message from the server.
 *
 * In general, synchronous messages can be arbitrary strings. However, most
 * often they are of the form <code>OK <i>[additional information]</i></code>
 * or <code>ERR <i>error code</i></code>. This class defines methods to 
 * recognize the message type and extract particular elements of common
 * messages.
 */
public class Message 
{
   private String msg;
   private String[] parts;
   
   /**
    * Constructs a message from a string.
    * @param msg the raw string version of the message.
    */
   public Message(String msg) 
   {
      this.msg = msg;
      parts = msg.split(" ");
   }

   /**
    * Returns this message in its raw form as a String.
    */
   public String toString()
   {
      return msg;
   }

   /**
    * Checks if this message indicates success.
    */
   public boolean isOK()
   {
      return parts[0].equals("OK");
   }

   /**
    * Returns a part of information embedded in a success message.
    * 
    * @param index index of the info
    * @return <code>index</code>th sequence of non-space characters delimited by
    * spaces, not counting the initial OK
    */
   public String getOKInfo(int index)
   {
      return parts[index + 1];
   }

   /**
    * Returns a part of information embedded in a success message as an
    * integer.
    * 
    * @param index index of the info
    * @return <code>index</code>th sequence of non-space characters delimited by
    * spaces, not counting the initial OK, converted to an integer
    */
   public int getOKIntInfo(int index)
   {
      return Integer.parseInt(parts[index + 1]);
   }

   /**
    * Check if this message indicates failure.
    */
   public boolean isError()
   {
      return parts[0].equals("ERR");
   }

   /**
    * Returns the error code associated with an error message.
    */
   public int getErrorCode()
   {
      return Integer.parseInt(parts[1]);
   }
}
