/*
 * Copyright (C) 2013 Darth Affe <http://wyrez.org> and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.wyrez.shootingstars.game;

import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.texture.Image;
import com.jme3.texture.Texture2D;
import com.sun.jna.Memory;
import java.nio.ByteBuffer;
import org.wyrez.shootingstars.factories.Materials;
import org.wyrez.shootingstars.mesh.CinemaHex;
import uk.co.caprica.vlcj.player.direct.BufferFormat;
import uk.co.caprica.vlcj.player.direct.DirectMediaPlayer;
import uk.co.caprica.vlcj.player.direct.RenderCallback;

/**
 *
 * @author Darth Affe
 */
public class Cinema extends Geometry implements RenderCallback {

    private final Image videoImage;
    private final Texture2D videoTexture;
    private final Object bufferLock = new Object();
    private ByteBuffer buffer;
    private int videoBufferSize;

    public Cinema(GameSettings settings) {
        this(settings, 1000f);
    }

    public Cinema(GameSettings settings, float radius) {
        this(settings, radius, Vector3f.ZERO);
    }

    public Cinema(GameSettings settings, float radius, Vector3f pos) {
        super("Cinema: " + settings.getVideoFile(), new CinemaHex(pos, radius,
                radius * ((float) settings.getVideoHeight() / (float) settings.getVideoWidth())));
        videoImage = new Image(settings.GetTextureFormat(), settings.getVideoWidth(), settings.getVideoHeight(), null);
        videoTexture = new Texture2D(videoImage);
        videoBufferSize = settings.getVideoWidth() * settings.getVideoHeight() * settings.getVideoDepth();
        Material mat = Materials.UNSHADED.create();
        mat.setTexture("ColorMap", videoTexture);
        this.setMaterial(mat);
        this.rotate(0f, FastMath.PI / 6f, 0f);
    }

    public void render() {
        synchronized (bufferLock) {
            videoImage.setData(buffer);
        }
    }

    @Override
    public void display(DirectMediaPlayer mediaPlayer, Memory[] nativeBuffers, BufferFormat bufferFormat) {
        synchronized (bufferLock) {
            buffer = nativeBuffers[0].getByteBuffer(0, videoBufferSize);
        }
    }
}
