package org.ourfilesystem.simpleui;

/*
OurFileSystem is a peer2peer file sharing program.
Copyright (C) 2012  Robert Gass

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.

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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.ourfilesystem.db.Peer;

public class PeerTable extends AbstractTableModel {
	private static final long serialVersionUID = 1L;
	
	private LinkedList<Peer> Peers;
	
	public PeerTable() {
		Peers = new LinkedList<Peer>();
	}
	
	public void addAllPeers(List<Peer> pl) {
		Peers.clear();
		Peers.addAll(pl);
		this.fireTableDataChanged();
	}
	
	public void addPeer(Peer p) {
		if (!Peers.contains(p)) {
			Peers.add(p);
			this.fireTableDataChanged();
		}
	}

	private String columns[] = {
			"Nickname",
			"Introduction",
			"Location",
			"Identity",
			"Signed by"
	};
	
	public String getColumnName(int col) {
		return columns[col];
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Class getColumnClass(int col) {
		return String.class;
	}
	
	@Override
	public int getColumnCount() {
		return columns.length;
	}

	@Override
	public int getRowCount() {
		return Peers.size();
	}
	
	public Peer getPeer(int row) {
		Iterator<Peer> i = Peers.iterator();
		Peer up = null;
		int cnt = 0;
		while (i.hasNext() && cnt <= row) {
			up = i.next();
			cnt++;
		}
		return up;
	}

	@Override
	public Object getValueAt(int row, int col) {
		Peer up = getPeer(row);
		if (up != null) {
			if (col == 0) {
				return up.getNickname();
			}
			else if (col == 1) {
				return up.getIntroduction();
			}
			else if (col == 2) {
				return up.getLocation();
			}
			else if (col == 3) {
				return up.getPeerKeysAndIdentity().getSignature().getDigest().toString().substring(0,10);
			}
			else if (col == 4) {
				return up.getPeerKeysAndIdentity().getSignature().getPeerIdentifier().toString().substring(0,10);
			}
		}
		return null;
	}

}
