package persistence.tag;

import persistence.csv.CSVSerializable;
import persistence.errors.PersistenceError;
import tag.Tag;
import tag.TagName;

import java.util.Optional;

public class TagEntity {

	private final String name;
	private Optional<String> additionalData = Optional.empty();

	public TagEntity(String name, String additionalData) {
		this.name = name;
		this.additionalData = Optional.of(additionalData);
	}

	public TagEntity(String csvString) {
		var splittedString = csvString.split(CSVSerializable.memberSeperator);

		if (splittedString.length == 0 || splittedString.length > 2) {
			throw new PersistenceError();
		}

		this.name = splittedString[0];

		if (splittedString.length == 2) {
			this.additionalData = Optional.of(splittedString[1]);
		}
	}

	public TagEntity(Tag tag) {
		this.name = tag.getName().name();
		this.additionalData = tag.getAdditionalData();

	}

	public String toCSVString() {
		return name + CSVSerializable.memberSeperator + additionalData.orElse("");
	}

	public Tag toTag(){
		return new Tag(new TagName(name),additionalData);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		TagEntity tagEntity = (TagEntity) o;

		if (name != null ? !name.equals(tagEntity.name) : tagEntity.name != null) return false;
		return additionalData != null
		       ? additionalData.equals(tagEntity.additionalData)
		       : tagEntity.additionalData == null;
	}

	@Override
	public int hashCode() {
		int result = name != null ? name.hashCode() : 0;
		result = 31 * result + (additionalData != null ? additionalData.hashCode() : 0);
		return result;
	}
}
