package com.github.simpletsdb;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class TimePoint
{
	private final String name;

	String[] columnNames;
	Object[] columnValues;

	public static class Builder
	{
		private final String seriesName;
		private final List<String> columnsNames = Lists.newArrayList();
		private List<Object> values;

		public Builder(final String seriesName)
		{
			this.seriesName = seriesName;
		}

		public Builder columns(final String... columnNames)
		{
			Preconditions.checkArgument(this.columnsNames.isEmpty(),
					"You can only call columns() once.");
			this.columnsNames.addAll(Arrays.asList(columnNames));
			return this;
		}

		public Builder row(final Object... values)
		{
			Preconditions.checkArgument(
					values.length == this.columnsNames.size(),
					"Value count differs from column count.");
			Preconditions.checkArgument(this.columnsNames.isEmpty(),
					"You can only call row() once.");
			this.values = Arrays.asList(values);
			return this;
		}

		public TimePoint build()
		{
			Preconditions.checkArgument(
					!Strings.isNullOrEmpty(this.seriesName),
					"Serie name must not be null or empty.");

			TimePoint serie = new TimePoint(this.seriesName);

			serie.columnNames = this.columnsNames
					.toArray(new String[this.columnsNames.size()]);

			if (this.values != null)
			{
				serie.columnValues = values.toArray();
			}
			return serie;
		}
	}

	private TimePoint(final String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return this.name;
	}

	public String[] getColumns()
	{
		return this.columnNames;
	}

	public Map<String, Object> getValues()
	{
		int column = 0;
		Map<String, Object> row = Maps.newHashMap();
		for (Object value : this.columnValues)
		{
			row.put(this.columnNames[column], value);
			column++;
		}
		return row;
	}

	@Override
	public String toString()
	{
		return Objects.toStringHelper(this.getClass()).add("name", this.name)
				.add("c", Arrays.deepToString(this.columnNames))
				.add("p", Arrays.deepToString(this.columnValues)).toString();
	}

}
