package ru.m.puzzlez.core;

import flash.geom.Point;
import flash.geom.Rectangle;
import ru.m.puzzlez.core.Part.Bounds;
import ru.m.puzzlez.core.Part.BoundType;

class GameUtil {

    public static function buildPreset(image:ImageSource):GamePreset {
        return {
            image:image,
            grid: {width: 8, height: 8},
            tableRect: new Rectangle(0, 0, 1128, 1128),
            //imageRect: new Rectangle(0, 0, 2304, 2304),
            imageRect: new Rectangle(0, 0, 1024, 1024),
        }
    }

    public static function buildState(preset:GamePreset):GameState {
        var parts:Array<Part> = [];
        var partWidth = preset.imageRect.width / preset.grid.width;
        var partHeight = preset.imageRect.height / preset.grid.height;
        var topLeft = new Point(
        (preset.tableRect.width - preset.imageRect.width) / 2,
        (preset.tableRect.height - preset.imageRect.height) / 2
        );
        for (x in 0...preset.grid.width) {
            for (y in 0...preset.grid.height) {
                var bounds:Bounds = {
                    left: BoundType.IN,
                    right: BoundType.OUT,
                    top: BoundType.IN,
                    bottom: BoundType.OUT,
                }
                if (x == 0) {
                    bounds.left = BoundType.NONE;
                }
                if (y == 0) {
                    bounds.top = BoundType.NONE;
                }
                if (x == preset.grid.width - 1) {
                    bounds.right = BoundType.NONE;
                }
                if (y == preset.grid.height - 1) {
                    bounds.bottom = BoundType.NONE;
                }
                var id = (x << 16) + y;
                var position = new Point(topLeft.x + x * partWidth, topLeft.y + y * partHeight);
                parts.push({
                    id: id,
                    gridX: x,
                    gridY: y,
                    position: position,
                    rect: new Rectangle(position.x, position.y, partWidth, partHeight),
                    bounds: bounds
                });
            }
        }
        return {
            preset: preset,
            parts: parts,
        }
    }
}
