// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.component;

import java.util.Objects;
import java.lang.ref.WeakReference;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

public class WeakComponentReference<ECS_TYPE, T extends Component<ECS_TYPE>>
{
    @Nonnull
    private final Store<ECS_TYPE> store;
    @Nonnull
    private final ComponentType<ECS_TYPE, T> type;
    @Nullable
    private Ref<ECS_TYPE> ref;
    private WeakReference<T> reference;
    
    WeakComponentReference(@Nonnull final Store<ECS_TYPE> store, @Nonnull final ComponentType<ECS_TYPE, T> type, @Nonnull final Ref<ECS_TYPE> ref, @Nonnull final T data) {
        this.store = store;
        this.type = type;
        this.ref = ref;
        this.reference = new WeakReference<T>(data);
    }
    
    @Nullable
    public T get() {
        T data = this.reference.get();
        if (data != null) {
            return data;
        }
        if (this.ref == null) {
            return null;
        }
        data = this.store.getComponent(this.ref, this.type);
        if (data != null) {
            this.reference = new WeakReference<T>(data);
        }
        return data;
    }
    
    @Nonnull
    public Store<ECS_TYPE> getStore() {
        return this.store;
    }
    
    @Nonnull
    public ComponentType<ECS_TYPE, T> getType() {
        return this.type;
    }
    
    @Nullable
    public Ref<ECS_TYPE> getEntityReference() {
        return this.ref;
    }
    
    void invalidate() {
        this.ref = null;
        this.reference.clear();
    }
    
    @Override
    public boolean equals(@Nullable final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || this.getClass() != o.getClass()) {
            return false;
        }
        final WeakComponentReference<?, ?> that = (WeakComponentReference<?, ?>)o;
        return this.store.equals(that.store) && this.type.equals(that.type) && Objects.equals(this.ref, that.ref);
    }
    
    @Override
    public int hashCode() {
        int result = this.store.hashCode();
        result = 31 * result + this.type.hashCode();
        result = 31 * result + ((this.ref != null) ? this.ref.hashCode() : 0);
        return result;
    }
    
    @Nonnull
    @Override
    public String toString() {
        return "WeakComponentReference{store=" + String.valueOf(this.store) + ", type=" + String.valueOf(this.type) + ", entity=" + String.valueOf(this.ref) + ", reference=" + String.valueOf(this.reference);
    }
}
