package org.kne.cloud.network.klalb.ui;

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.kne.cloud.klalb.uitool.XDefaultListModel;
import org.kne.cloud.network.MultiProtocolSocketAddress;
import org.kne.cloud.network.ipv6.IPv6Address;
import org.kne.cloud.network.klalb.KLALBController;
import org.kne.cloud.network.srv6.KLALBRoutingProtocol;
import org.kne.cloud.network.srv6.KLALBRoutingProtocolAPIClient;
import javax.swing.JTabbedPane;
import javax.swing.JList;
import javax.swing.JMenuItem;

import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.ActionEvent;

public class NodeInformationPanel extends JPanel {
	private IPv6Address address;
	private KLALBRoutingProtocolAPIClient client;
	private KLALBController controller;
	private Image image;
	
	private XDefaultListModel<MultiProtocolSocketAddress> listModel=new XDefaultListModel<>();
	public KLALBController getController() {
		return controller;
	}
	public IPv6Address getAddress() {
		return address;
	}
	
	public Image getImage() {
		return image;
	}
	public NodeInformationPanel (KLALBController controller,IPv6Address address,Image image) {
		this.controller=controller;
		this.address=address;
		this.image=image;
		setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		add(tabbedPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout(0, 0));
		tabbedPane.addTab(UIEnv.getRsb().getString("overview"), null, panel, null);
		
		JTextArea overviewArea = new JTextArea();
		overviewArea.setEditable(false);
		overviewArea.setLineWrap(true);
		overviewArea.setWrapStyleWord(true);
		overviewArea.setFont(UIEnv.getFont().deriveFont(14.0f));
		overviewArea.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
		String dname=controller.getIpv6Router().getKlalbRouteProtol().getDeviceName(address);
		String ddesc=null;
		if(address.equals(controller.getIpv6Router().getLocator().getAddress())&&controller.getConfigItem()!=null) {
			ddesc=controller.getConfigItem().getDeviceDescription();
			if(ddesc!=null&&ddesc.isEmpty()) {
				ddesc=null;
			}
		}
		overviewArea.setText(buildOverviewText(dname, ddesc));
		panel.add(new JScrollPane(overviewArea), BorderLayout.CENTER);
		
		JPanel panel_1 = new JPanel();
		panel_1.setLayout(new BorderLayout(0, 0));
		panel_1.add(scrollPane);
		
		JList<MultiProtocolSocketAddress> list = new JList<MultiProtocolSocketAddress>(listModel);
		list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		scrollPane.setViewportView(list);
		tabbedPane.addTab(UIEnv.getRsb().getString("openlinetable"), null, panel_1, null);
		
		JButton btnNewButton = new JButton(UIEnv.getRsb().getString("addline"));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<MultiProtocolSocketAddress> select=list.getSelectedValuesList();
				controller.addRemoteLines(select);
			}
		});
		btnNewButton.setEnabled(false);
		JPopupMenu jpop=new JPopupMenu();
		JMenuItem copy=new JMenuItem(UIEnv.getRsb().getString("copy"));
		copy.setEnabled(false);
		list.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				List<MultiProtocolSocketAddress> select=list.getSelectedValuesList();
				btnNewButton.setEnabled( !select.isEmpty()) ;
				copy.setEnabled(!select.isEmpty());
			}
		});
		copy.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				StringBuilder sb=new StringBuilder();
				List<MultiProtocolSocketAddress> select=list.getSelectedValuesList();
				for (MultiProtocolSocketAddress multiProtocolSocketAddress : select) {
					sb.append(multiProtocolSocketAddress);
					sb.append('\n');
				}
				Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(sb.toString()), null);
			}
		});
		jpop.add(copy);
		list.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				if(e.getButton()==MouseEvent.BUTTON3) {
					jpop.show(list, e.getX(), e.getY());
				}
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
					jpop.show(list, e.getX(), e.getY());
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				// TODO 自动生成的方法存根
				
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO 自动生成的方法存根
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.isPopupTrigger()) {
					jpop.show(list, e.getX(), e.getY());
				}
			}
		});
		
		panel_1.add(btnNewButton, BorderLayout.SOUTH);
		
		client=new KLALBRoutingProtocolAPIClient(controller.getIpv6Router().getKlalbRouteProtol());
		try {
			client.requestNodeInfoFull(new InetSocketAddress( address.toInet6Address(), KLALBRoutingProtocol.DEFAULT_PORT), (info)->{
				listModel.clear();
				for (MultiProtocolSocketAddress multiProtocolSocketAddress : info.getOpenLines()) {
					listModel.addElement(multiProtocolSocketAddress);
				}
				// 用对端返回的设备名称/描述更新概览（旧版本节点无该字段时保留原显示）
				String dn=info.getDeviceName();
				if(dn==null||dn.isEmpty()) {
					dn=controller.getIpv6Router().getKlalbRouteProtol().getDeviceName(address);
				}
				String dd=info.getDeviceDescription();
				if(dd!=null&&dd.isEmpty()) {
					dd=null;
				}
				overviewArea.setText(buildOverviewText(dn, dd));
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String buildOverviewText(String dname,String ddesc) {
		StringBuilder sb=new StringBuilder();
		sb.append(UIEnv.getRsb().getString("ipv6addr")).append(": ").append(address.toCompressedString()).append('\n');
		if(dname!=null&&!dname.isEmpty()) {
			sb.append('\n').append(UIEnv.getRsb().getString("devicename")).append(": ").append(dname).append('\n');
		}
		if(ddesc!=null&&!ddesc.isEmpty()) {
			sb.append('\n').append(UIEnv.getRsb().getString("devicedescription")).append(":\n").append(ddesc).append('\n');
		}
		return sb.toString();
	}
	public Icon getIcon() {
		return new ImageIcon(image);
	}
}
