All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.legendofdragoon.modloader.registries.Registries Maven / Gradle / Ivy

There is a newer version: 3.0.4
Show newest version
package org.legendofdragoon.modloader.registries;

import org.legendofdragoon.modloader.events.EventManager;
import org.legendofdragoon.modloader.events.registries.RegistryEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

public class Registries {
  private final EventManager events;
  private final List> registries = new ArrayList<>();
  private final Map, Function, RegistryEvent.Register>> registryEvents = new HashMap<>();

  protected Registries(final EventManager events, final Consumer access) {
    this.events = events;
    access.accept(new Access());
  }

  protected  Registry addRegistry(final Registry registry, final Function, RegistryEvent.Register> registryEvent) {
    final MutableRegistry mutableRegistry = (MutableRegistry)registry;
    this.registries.add(mutableRegistry);
    //noinspection unchecked
    this.registryEvents.put(mutableRegistry, (Function, RegistryEvent.Register>)(Object)registryEvent);
    return registry;
  }

  public class Access {
    private Access() { }

    private final Set> initialized = new HashSet<>();

    public  void initialize(final Registry registry) {
      if(this.initialized.contains(registry)) {
        throw new IllegalStateException("Registry " + registry + " already initialized");
      }

      final MutableRegistry mutableRegistry = (MutableRegistry)registry;

      if(!Registries.this.registryEvents.containsKey(mutableRegistry)) {
        throw new IllegalArgumentException("Unknown registry " + registry);
      }

      Registries.this.events.postEvent(Registries.this.registryEvents.get(mutableRegistry).apply(mutableRegistry));
      mutableRegistry.lock();
      this.initialized.add(mutableRegistry);
    }

    public void initializeRemaining() {
      for(final MutableRegistry registry : Registries.this.registries) {
        if(!this.initialized.contains(registry)) {
          this.initialize(registry);
        }
      }
    }

    public void reset() {
      this.initialized.clear();

      for(final MutableRegistry registry : Registries.this.registries) {
        registry.reset();
      }
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy