/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 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 CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.datastructure;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Represents a GML id. Additionally contains information whether this id was
 * generated by city doctor
 * 
 * @author Matthias Betz
 *
 */
public class GmlId implements Serializable {

	private static final long serialVersionUID = 4273817255150972966L;

	/* prefixes for generation */
	private static final String GENERAL_GEN = "CityDoctor_%d_%d";
	private static final AtomicInteger ID_COUNTER = new AtomicInteger();

	private String gmlString;
	private boolean generated;

	public GmlId(String gmlId) {
		this(gmlId, false);
	}

	private GmlId(String gmlId, boolean generated) {
		if (gmlId == null || gmlId.isEmpty()) {
			throw new IllegalArgumentException("GmlId may not be null or empty. If no GmlId is given generate one");
		}
		this.gmlString = gmlId;
		this.generated = generated;
	}

	@Override
	public String toString() {
		return gmlString;
	}

	public String getGmlString() {
		return gmlString;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (generated ? 1231 : 1237);
		result = prime * result + ((gmlString == null) ? 0 : gmlString.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		GmlId other = (GmlId) obj;
		if (generated != other.generated) {
			return false;
		}
		if (gmlString == null) {
			if (other.gmlString != null) {
				return false;
			}
		} else if (!gmlString.equals(other.gmlString)) {
			return false;
		}
		return true;
	}

	/**
	 * Determines if the GML-ID was generated by CityDoctor or not.
	 * 
	 * @return True if it was generated, otherwise false.
	 */
	public boolean isGenerated() {
		return generated;
	}

	public static GmlId generateId() {
		return new GmlId(String.format(GENERAL_GEN, System.currentTimeMillis(), ID_COUNTER.getAndIncrement()), true);
	}

}
