package ru.m.puzzlez.core;

import flash.geom.Point;
import haxework.signal.Signal;

class Game implements IGame {
    public var state(default, null):GameState;
    public var signal(default, null):Signal<GameEvent>;

    private var partsById:Map<Int, Part>;

    public function new(preset:GamePreset) {
        state = GameUtil.buildState(preset);
        partsById = new Map();
        for (part in state.parts) {
            partsById[part.id] = part;
        }
        signal = new Signal();
        signal.connect(onGameEvent);
    }

    public function start():Void {
        signal.emit(GameEvent.START(state));
    }

    private static function distance(a:Point, b:Point):Float {
        var diff = a.subtract(b);
        return Math.abs(diff.x) + Math.abs(diff.y);
    }

    private function onGameEvent(event:GameEvent):Void {
        switch event {
            case GameEvent.PART_MOVE(id, position):
                signal.emit(GameEvent.PART_MOVED(id, position));
            case GameEvent.PART_PUT(id, position):
                var part = partsById[id];
                var d = distance(part.position, position);
                if (d < 50) {
                    signal.emit(GameEvent.PART_MOVED(id, part.position));
                } else {
                    signal.emit(GameEvent.PART_MOVED(id, position));
                }
            case _:
        }
    }

    public function stop():Void {

    }

    public function dispose():Void {
        signal.dispose();
    }
}
