package com.bocloud.ims.entity.resource.hmc;

import java.util.Arrays;
import java.util.Objects;
import java.util.function.Function;

public class HmdGenericEuqal<T extends HmdGenericEntity> {

	private final T t;
	private final Function<T, Object>[] getters;

	public HmdGenericEuqal(T t, Function<T, Object>... getters) {
		this.t = t;
		this.getters = getters;
	}

	public T getT() {
		return t;
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || this.getClass() != o.getClass()) {
			return false;
		}
		HmdGenericEuqal<T> that = (HmdGenericEuqal<T>) o;
		if (this.t == null && that.t == null) {
			return true;
		}
		if (this.t == null || that.t == null) {
			return false;
		}
		if (this.t == that.t) {
			return true;
		}
		if (this.getters == null && that.getters == null) {
			return this.t.equals(that.t);
		}
		if (this.getters == null || that.getters == null) {
			return false;
		}
		if (this.getters.length != that.getters.length) {
			return false;
		}
		Object[] thisObjects = Arrays.stream(this.getters).map(getter -> getter.apply(this.t)).toArray(Object[]::new);
		Object[] thatObjects = Arrays.stream(that.getters).map(getter -> getter.apply(that.t)).toArray(Object[]::new);
		return Arrays.equals(thisObjects, thatObjects);
	}

	@Override
	public int hashCode() {
		if (this.getters == null) {
			return Objects.hashCode(t);
		}

		Object[] thisObjects = Arrays.stream(this.getters).map(getter -> getter.apply(this.t)).toArray(Object[]::new);
		return Arrays.hashCode(thisObjects);
	}
}
