package net.woodyfolsom.msproj.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import net.woodyfolsom.msproj.Action;
import net.woodyfolsom.msproj.GameConfig;
import net.woodyfolsom.msproj.GameState;
import net.woodyfolsom.msproj.Player;
import net.woodyfolsom.msproj.StandAloneGame;
import net.woodyfolsom.msproj.sfx.SfxPlayer;

public class Goban extends JFrame {
	
	private static final long serialVersionUID = 1L;

	private static AtomicInteger openWindows = new AtomicInteger(0);
	
	private GridPanel gridPanel;
	private SfxPlayer sfxPlayer;
	
	public Goban(GameConfig gameConfig, Player guiPlayer, String gameName) {
		super(gameName);
		
		setLayout(new BorderLayout());
		
		addWindowListener(new WindowAdapter() {
			@Override
	        public void windowClosing(WindowEvent e) {
				sfxPlayer.cleanup();
				int windowsLeftOpen = openWindows.addAndGet(-1);
				if (windowsLeftOpen < 1) {
					System.exit(StandAloneGame.EXIT_USER_QUIT);
				}
	        }
		});
		
		try {
			sfxPlayer = new SfxPlayer();
		} catch (Exception ex) {
			System.out.println("Unable to initialize click sound due to: " + ex.getMessage());
		}
		
		this.gridPanel = new GridPanel(gameConfig, guiPlayer, sfxPlayer);
		add(gridPanel,BorderLayout.CENTER);
		
		JButton passBtn = new JButton("Pass");
		JButton resignBtn = new JButton("Resign");
		
		passBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				gridPanel.addAction(Action.PASS);
			}});
		
		resignBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				gridPanel.addAction(Action.RESIGN);
			}});
		
		JPanel bottomPanel = new JPanel();
		bottomPanel.add(passBtn);
		bottomPanel.add(resignBtn);
		
		add(bottomPanel, BorderLayout.SOUTH);

		setVisible(true);
		openWindows.addAndGet(1);
		pack();
	}

	public Action getAction() {
		return gridPanel.getAction();
	}
	
	public void setGameState(GameState gameState) {
		gridPanel.setGameState(gameState);
	}

}