package ru.m.puzzlez.view;

import haxework.view.data.DataView;
import haxework.view.group.VGroupView;
import haxework.view.ImageView;
import haxework.view.utils.DrawUtil;
import openfl.utils.Assets;
import openfl.utils.AssetType;
import ru.m.puzzlez.core.Game;
import ru.m.puzzlez.core.GameUtil;
import ru.m.puzzlez.core.IGame;
import ru.m.puzzlez.render.IRender;

@:template class PuzzlezAppView extends VGroupView {

    @:view private var images:DataView<String, ImageView>;
    @:view private var render:IRender;
    private var game:IGame;

    public function new() {
        super();
        images.data = Assets.list(AssetType.IMAGE);
    }

    private function imageViewFactory(index:Int, image:String):ImageView {
        var result = new ImageView();
        result.stretch = false;
        result.fillType = FillType.COVER;
        result.geometry.width = 192;
        result.geometry.height = 128;
        result.image = Assets.getBitmapData(image);
        return result;
    }

    public function start(image:String):Void {
        stop();
        game = new Game(GameUtil.buildPreset(image));
        game.signal.connect(render.onGameEvent);
        render.signal.connect(game.signal.emit);
        game.start();
    }

    public function stop():Void {
        if (game != null) {
            render.signal.disconnect(game.signal.emit);
            game.stop();
            game.dispose();
            game = null;
        }
    }
}
