package mindustry.tools;

import arc.files.*;
import arc.graphics.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.serialization.*;

import java.io.*;

/** Java port of https://github.com/GglLfr/tile-gen/blob/master/src/main.rs */
public class ImageTileGenerator{
    private static final int layoutWidth = 384, layoutHeight = 128;
    private static final Pixmap layout = new Pixmap(Base64Coder.decode("[encoded data, 5132 characters]"));

    public static void generate(Fi path, String name, Fi outputDir) throws IOException{
        Pixmap image = new Pixmap(path);

        try{
            int width = image.width, height = image.height;

            if(width % 4 != 0 || height % 4 != 0) throw new IOException("Image dimensions are not divisible by 4: " + width + "x" + height);
            if(width != height) throw new IOException("Image is not square: " + width + "x" + height);

            int cellSize = width / 4;

            IntIntMap colorToPosition = new IntIntMap();

            for(int x = 0; x < 4; x++){
                for(int y = 0; y < 4; y++){
                    colorToPosition.put(layout.get(x * layoutWidth / 12, y * layoutHeight / 4), Point2.pack(x * width / 4, y * height / 4));
                }
            }

            int outWidth = width / 4 * 12, outHeight = height;
            Pixmap out = new Pixmap(outWidth, outHeight);

            for(int cx = 0; cx < 12; cx++){
                for(int cy = 0; cy < 4; cy++){
                    for(int rx = 0; rx < cellSize; rx++){
                        for(int ry = 0; ry < cellSize; ry++){
                            int point = colorToPosition.get(layout.get(
                                (cx * cellSize + rx) * layoutWidth / (width * 3),
                                (cy * cellSize + ry) * layoutHeight / height
                            ), -1);

                            if(point != -1){
                                int sx = Point2.x(point), sy = Point2.y(point);
                                out.set(cx * cellSize + rx, cy * cellSize + ry, image.get(sx + rx, sy + ry));
                            }
                        }
                    }
                }
            }

            for(int i = 0; i < 47; i++){
                int cx = i % 12, cy = i / 12;
                Pixmap cropped = out.crop(cx * cellSize, cy * cellSize, cellSize, cellSize);
                outputDir.child(name + "-" + i + ".png").writePng(cropped);
                cropped.dispose();
            }

            out.dispose();
        }finally{
            image.dispose();
        }
    }
}
