package ac.essex.ooechs.problems.woods.util;

import ac.essex.ooechs.lcs.Payoff;
import ac.essex.ooechs.problems.woods.WoodsEnvironment;
import ac.essex.ooechs.problems.woods.Woods2Environment;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * <p/>
 * 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 2
 * of the License, or (at your option) any later version,
 * provided that any use properly credits the author.
 * 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 at http://www.gnu.org
 * </p>
 *
 * @author Olly Oechsle, University of Essex, Date: 16-Jan-2008
 * @version 1.0
 */
public class WoodsGUI extends JFrame {

    JLabel area = new JLabel();

    WoodsEnvironment e;

    int steps = 0;

    JLabel status;

    public WoodsGUI() {

        this.e = new Woods2Environment();

        e.initialise();

        area = new JLabel();
        area.setHorizontalAlignment(JLabel.HORIZONTAL);
        BufferedImage image = e.getImage();
        area.setIcon(new ImageIcon(image));

        Container c = getContentPane();

        status = new JLabel(e.getName () + " Interactive Environment. Use NUMPAD keys to move");

        c.add(area, BorderLayout.CENTER);

        c.add(status, BorderLayout.SOUTH);

        addKeyListener(new KeyAdapter() {

            public void keyReleased(KeyEvent e) {

                if (e.getKeyCode() == 104) sendAction(WoodsEnvironment.N);
                if (e.getKeyCode() == 105) sendAction(WoodsEnvironment.NE);
                if (e.getKeyCode() == 102) sendAction(WoodsEnvironment.E);
                if (e.getKeyCode() == 99) sendAction(WoodsEnvironment.SE);
                if (e.getKeyCode() == 98) sendAction(WoodsEnvironment.S);
                if (e.getKeyCode() == 97) sendAction(WoodsEnvironment.SW);
                if (e.getKeyCode() == 100) sendAction(WoodsEnvironment.W);
                if (e.getKeyCode() == 103) sendAction(WoodsEnvironment.NW);

            }

        });

        Insets i = getInsets();

        setSize(image.getWidth() + 25, image.getHeight()  + 50);
        setVisible(true);
        setTitle(e.getName());

    }

    public void sendAction(int id) {
        Payoff p = e.takeAction(new ac.essex.ooechs.lcs.Action(id));
        steps++;
        if (p.isFinished()) {
            e.initialise();
            status.setText("Found food!");
            steps = 0;
        } else {
            status.setText(steps + " step(s)");
        }
        area.setIcon(new ImageIcon(e.getImage()));
    }

    public static void main(String[] args) {
        new WoodsGUI();
    }


}
