#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct s_String {
	//Notre chaine
	char *str;

	//Nos Methodes
	size_t (*length)(struct s_String *this);
	char (*get)(struct s_String *this, int pos);
	void (*replace)(struct s_String *this, int pos, char newChar);
	void (*add)(struct s_String *this, char newChar);
	void (*destroy)(struct s_String *this);

}String;

static size_t length(String *this) {
	return strlen(this->str);
}

static char get(String *this, int pos) {
	return this->str[pos];
}

static void destroy(String *this) {
	free(this->str);
	this->str = NULL;
}


static void replace(String *this, int pos, char newChar) {
	this->str[pos] = newChar;
}

static void add(String *this, char newChar) {
	char *newStr;

	//Bien sur les mallocs doivents etre verifés
	newStr = malloc(sizeof(char) * (this->length(this) + 2));
	strcpy(newStr, this->str);
	strncat(newStr, &newChar, 1);
	free(this->str);
	this->str = newStr;
}

String *create(char *s) {

	String *this;

	this = malloc(sizeof(String));
	this->length = &length;
	this->get = &get;
	this->replace = &replace;
	this->add = &add;
	this->destroy = &destroy;
	/* Copie de la chaine au cas ou c'est une chaine constante */
	this->str = malloc((strlen(s) + 1) * sizeof(char));
	strcpy(this->str, s);
	return this;
}

int main(void) {
	String *chaine = create("Coucou les amis");
	printf("taille de la chaine : %zd\n", chaine->length(chaine));
	printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
	chaine->replace(chaine, 0, 'T');
	printf("Je remplace le premiere char par un T\n");
	printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
	printf("J\'ajoute le caractere '&' a la fin de la chaine\n");
	chaine->add(chaine, '&');
	printf("La chaine est maintenant %s\n", chaine->str);

	chaine->destroy(chaine);

	free(chaine);

	return 0;
}