package com.zivilon.cinder_loe.world;

import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ModContainer;
import lotr.common.LOTRDimension;
import lotr.common.LOTRMod;
import lotr.common.world.biome.LOTRBiome;
import lotr.common.world.genlayer.LOTRGenLayerWorld;
import org.apache.logging.log4j.Level;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class CinderGenLayerWorld extends LOTRGenLayerWorld {
    private static byte[] biomeImageData;

    public CinderGenLayerWorld() {
        super();
        if (!LOTRGenLayerWorld.loadedBiomeImage()) {
            try {
                BufferedImage biomeImage = null;
                String imageName = "assets/lotr/map/map.png";
                ModContainer mc = LOTRMod.getModContainer();
                if (mc.getSource().isFile()) {
                    ZipFile zip = new ZipFile(mc.getSource());
                    Enumeration<? extends ZipEntry> entries = zip.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (!entry.getName().equals(imageName)) continue;
                        biomeImage = ImageIO.read(zip.getInputStream(entry));
                    }
                    zip.close();
                } else {
                    File file = new File(LOTRMod.class.getResource("/" + imageName).toURI());
                    biomeImage = ImageIO.read(new FileInputStream(file));
                }
                if (biomeImage == null) {
                    throw new RuntimeException("Could not load Cinder biome map image");
                }
                imageWidth = biomeImage.getWidth();
                imageHeight = biomeImage.getHeight();
                int[] colors = biomeImage.getRGB(0, 0, imageWidth, imageHeight, null, 0, imageWidth);
                biomeImageData = new byte[imageWidth * imageHeight];
                for (int i = 0; i < colors.length; ++i) {
                    int color = colors[i];
                    Integer biomeID = LOTRDimension.MIDDLE_EARTH.colorsToBiomeIDs.get(color);
                    if (biomeID != null) {
                        CinderGenLayerWorld.biomeImageData[i] = (byte)biomeID.intValue();
                        continue;
                    }
                    FMLLog.log((Level) Level.ERROR, (String)("Found unknown biome on map " + Integer.toHexString(color)), (Object[])new Object[0]);
                    CinderGenLayerWorld.biomeImageData[i] = (byte) LOTRBiome.ocean.biomeID;
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
