package com.thebrokenrail.gestus.emote;

import com.thebrokenrail.gestus.emote.exception.EmoteLoadingException;
import com.thebrokenrail.gestus.emote.exception.EmoteSyntaxException;
import net.minecraft.resource.Resource;
import net.minecraft.resource.ResourceManager;
import net.minecraft.resource.SynchronousResourceReloadListener;
import net.minecraft.util.Identifier;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public final class EmoteRegistry {
    private static final Map<Identifier, Emote> map = new HashMap<>();

    private static final String DATA_TYPE = "emotes";
    private static final String FILE_EXTENSION = ".emote";

    public static class ReloadListener implements SynchronousResourceReloadListener {
        public static final ReloadListener INSTANCE = new ReloadListener();

        private ReloadListener() {
        }

        @Override
        public void apply(ResourceManager manager) {
            EmoteRegistry.reload(manager);
        }
    }

    public static void reload(ResourceManager resourceManager) throws EmoteLoadingException {
        map.clear();

        Collection<Identifier> files = resourceManager.findResources(DATA_TYPE, str -> str.endsWith(FILE_EXTENSION));
        for (Identifier file : files) {
            Identifier id = new Identifier(file.getNamespace(), file.getPath().substring(DATA_TYPE.length() + 1, file.getPath().length() - FILE_EXTENSION.length()));

            try {
                Resource resource = resourceManager.getResource(file);

                InputStream inputStream = resource.getInputStream();

                List<String> result = new ArrayList<>();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                for (String line; (line = reader.readLine()) != null; ) {
                    result.add(line);
                }
                reader.close();

                Emote emote = new Emote(result.toArray(new String[0]));

                map.put(id, emote);
            } catch (IOException | EmoteSyntaxException e) {
                throw new EmoteLoadingException(id, e);
            }
        }
    }

    public static Emote get(Identifier id) {
        return map.get(id);
    }

    public static Set<Identifier> getAll() {
        return map.keySet();
    }
}
