/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2008 - 2019 ScalAgent Distributed Technologies
 * Copyright (C) 2008 - 2009 CNES
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s):
 */
package org.ow2.joram.mom.amqp.marshalling;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class LongStringHelper {

  public static class ByteArrayLongString implements LongString {
    /** define serialVersionUID for interoperability */
    private static final long serialVersionUID = 1L;
    
    byte[] bytes;

    public ByteArrayLongString(byte[] bytes) {
      this.bytes = bytes;
    }

    public boolean equals(Object o) {
      if (o instanceof LongString) {
        LongString other = (LongString) o;
        return Arrays.equals(this.bytes, other.getBytes());
      }

      return false;
    }

    public int hashCode() {
      return Arrays.hashCode(this.bytes);
    }

    public byte[] getBytes() {
      return bytes;
    }

    public InputStream getStream() throws IOException {
      return new ByteArrayInputStream(bytes);
    }

    public long length() {
      return bytes.length;
    }

    public String toString() {
      try {
        return new String(bytes, "utf-8");
      } catch (UnsupportedEncodingException e) {
        throw new Error("utf-8 encoding support required");
      }
    }
  }

  public static LongString asLongString(String s) {
    try {
      return new ByteArrayLongString(s.getBytes("utf-8"));
    } catch (UnsupportedEncodingException e) {
      throw new Error("utf-8 encoding support required");
    }
  }

  public static LongString asLongString(byte[] bytes) {
    return new ByteArrayLongString(bytes);
  }
}
