package de.hfu.anybeam.desktop;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.swing.JList;

import de.hfu.anybeam.networkCore.Client;
import de.hfu.anybeam.networkCore.NetworkEnvironmentListener;

public class SearchWindow implements NetworkEnvironmentListener {

	private JFrame frame;
	private JList clientList;

	/**
	 * Create the application.
	 */
	public SearchWindow() {
		try {
			NetworkEnvironmentManager.addNetworkEnvironmentListener(this);
			NetworkEnvironmentManager.getNetworkEnvironment().startClientSearch(365, TimeUnit.DAYS, 3, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		initialize();
		
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				try {
					NetworkEnvironmentManager.getNetworkEnvironment().dispose();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 300, 512);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));
		
		clientList = new JList();
		frame.getContentPane().add(clientList);
		
	}
	
	public JFrame getFrame() {
		return frame;
	}
	
	private void updateView() {
		DefaultListModel model = new DefaultListModel();

		List<Client> clients = new ArrayList<Client>();
		try {
			clients = NetworkEnvironmentManager.getNetworkEnvironment().getClientList();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for(int i=0; i<clients.size(); i++) {
			model.add(i, clients.get(i).getName());
		}
		
		this.clientList.setModel(model);
	}

	@Override
	public void clientFound(Client c) {
		updateView();	
	}

	@Override
	public void clientUpdated(Client c) {
		updateView();		
	}

	@Override
	public void clientLost(Client c) {
		updateView();		
	}

	@Override
	public void clientListCleared() {
		updateView();		
	}

	@Override
	public void clientSearchStarted() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void clientSearchDone() {
		// TODO Auto-generated method stub
		
	}

}
