package pl.helion.j2mepp.zdalnakamera;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.GUIControl;
import javax.microedition.media.control.VideoControl;
import pl.helion.j2mepp.zdalnakamera.dodatkowe.NadawcaObrazTask;
import pl.helion.j2mepp.zdalnakamera.dodatkowe.ObrazTask;

public class ObrazForm extends Form {
    private ImageItem obraz = new ImageItem("Obraz:", null, ImageItem.LAYOUT_EXPAND, "Trwa ładowanie...");
    private Command zakoncz = new Command("Zakończ", Command.BACK, 0);
    private Timer zegar = new Timer();
    private Player kamera;
    private VideoControl kontrolka;

    final int OPOZNIENIE = 1000;
    final int OKRES = 15000;

    private String SID;

    public ObrazForm(CommandListener l) {
        super("Obraz");
        this.append(obraz);
        this.addCommand(zakoncz);
        this.setCommandListener(l);
    }

    public void start(ObrazTask zadanie) {
        zadanie.setWlasciciel(this);
        zegar.schedule(zadanie, OPOZNIENIE, OKRES);
    }

    public boolean ustawKamere() {
        try {
            kamera = Manager.createPlayer("capture://video");
            kamera.realize();
            kamera.prefetch();
            kontrolka = (VideoControl)kamera.getControl("VideoControl");
            kontrolka.initDisplayMode(GUIControl.USE_GUI_PRIMITIVE, null);
            kamera.start();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public byte[] getZdjecie() {
        try {
            return this.kontrolka.getSnapshot(null);
        } catch (MediaException me) {
            me.printStackTrace();
        }
        return new byte[0];
    }

    public void pokazObraz(Image obraz) {
        this.obraz.setImage(obraz);
    }

    public void setSID(String sid) {
        this.SID = sid;
        if (this.size() > 1)
            this.delete(1);
        this.append("SID: " + sid);
    }
}
