package ru.m.puzzlez.view;

import haxework.net.JsonLoader;
import haxework.view.data.DataView;
import haxework.view.group.VGroupView;
import haxework.view.ImageView;
import haxework.view.list.ScrollBarView;
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.core.ImageSource;
import ru.m.puzzlez.render.IRender;
import ru.m.puzzlez.render.RenderUtil;

typedef PixabayResponse = {
    hits:Array<{
        largeImageURL:String,
    }>
}

@:template class PuzzlezAppView extends VGroupView {

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

    public function new() {
        super();
        images.data = [for (name in Assets.list(AssetType.IMAGE)) ASSET(name)];
        render.scale = 0.75;
        scale.position = render.scale - scale.ratio;

        /*new JsonLoader<PixabayResponse>()
        .GET('https://pixabay.com/api/?key=14915210-5eae157281211e0ad28bc8def&category=nature')
        .then(function(result:PixabayResponse) {
            images.data = images.data.concat([for (item in result.hits) URL(item.largeImageURL)]);
        });*/
    }

    private function imageViewFactory(index:Int, image:ImageSource):ImageView {
        var result = new ImageView();
        result.stretch = false;
        result.fillType = FillType.COVER;
        result.setSize(192, 128);
        RenderUtil.resolveImage(image).then(function(image) result.image = image);
        return result;
    }

    public function setScale(value:Float):Void {
        render.scale = value + scale.ratio;
    }

    public function start(image:ImageSource):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;
        }
    }
}
