/*
 * @(#)String.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 22.04.2002
 */

#include <stdlib.h>
#include <string.h>
#include "Error.h"
#include "Log.h"
#include "String.h"
#include "StringBuffer.h"

String::String() {
	buf = new StringBuffer(0);
	bytes = NULL;
}

String::String(const String &str) {
	buf = new StringBuffer(*str.buf);
	bytes = NULL;
}

String::String(String *str) {
	buf = str->buf;
	str->buf = NULL;

	bytes = str->bytes;
	str->bytes = NULL;

	delete str;
}

String::String(const char *str) {
	buf = new StringBuffer(str);
	bytes = NULL;
}

String::String(StringBuffer &buffer) {
	buf = new StringBuffer(buffer);
	bytes = NULL;
}

String::~String() {
	if (buf != NULL)
		delete buf;
	if (bytes != NULL)
		delete[] bytes;
}

String &String::operator=(String &str) {
	log.debug("String", "%x::operator=(%s)", this, str.getBytes());
	if (&str == this)
		return str;

	if (bytes != NULL) {
		delete[] bytes;
		bytes = NULL;
	}
	delete buf;
	buf = new StringBuffer(*str.buf);
	log.debug("String", "duplicated String %x", &str);
	return *this;
}

String &String::operator=(String *str) {
	StringBuffer *oldBuf = buf;
	buf = str->buf;
	str->buf = oldBuf;

	char *oldBytes = bytes;
	bytes = str->bytes;
	str->bytes = oldBytes;

	delete str;
	return *this;
}

String &String::operator=(const char *str) {
	return this->operator=(new String(str));
}

String &String::operator+(char c) {
	buf->append(c);
	return *this;
}

String &String::operator+(int i) {
	buf->append(i);
	return *this;
}

String &String::operator+(String &str) {
	buf->append(str.getBytes());
	return *this;
}

String &String::operator+(const char *str) {
	buf->append(str);
	return *this;
}

int String::charAt(int index) {
	return buf->charAt(index);
}

int String::compareToIgnoreCase(const char *str) {
	return strcasecmp(getBytes(), str);
}

int String::endsWith(const char *suffix) {
	return buf->endsWith(suffix);
}

int String::equals(const char *str) {
	return buf->equals(str);
}

int String::equalsIgnoreCase(const char *str) {
	return buf->equalsIgnoreCase(str);
}

const char *String::getBytes() {
	if (bytes != NULL)
		delete[] bytes;

	int len = buf->length();
	bytes = new char[len + 1];
	for (int i = 0; i < len; i++)
		bytes[i] = buf->charAt(i);
	bytes[len] = 0;

	return bytes;
}

int String::indexOf(const char *str) {
	return buf->indexOf(str);
}

int String::length() {
	return buf->length();
}

int String::startsWith(const char *prefix) {
	return buf->startsWith(prefix);
}
