package jp.ac.kyutech.mns.ist;

import java.awt.Color;
import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;

import javax.swing.JOptionPane;


public class SimpleATN_UDPNoticeReceiver implements Runnable {
	public static int UDP_CHATPORT = 15658; //ATNGK(J)に対応する数字
	public static int BUFFER_SIZE = 2048;
	public SimpleATN satn;
	SimpleDateFormat sdf;
	Thread thread;
	public SimpleATN_UDPNoticeReceiver(SimpleATN _satn){
		satn = _satn;
		sdf = new SimpleDateFormat("MM/dd hh:mm");
		thread = new Thread(this);
		thread.start();
	}
	public void run() {

		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket(UDP_CHATPORT);
		} catch (SocketException e) {
//			e.printStackTrace();
			if (e instanceof BindException){
				System.out.println("Trying to shutdown other SimpleATN...");
				datagramSocket = recoverAfterPreviousShutdown();

//				try {
//					datagramSocket = new DatagramSocket(UDP_CHATPORT+1);
//				} catch (SocketException e1) {
//					e1.printStackTrace();
//				}
				
			}
		}

		byte[] data = new byte[BUFFER_SIZE];

		while(true){
			DatagramPacket datagramPacket = new DatagramPacket(data, BUFFER_SIZE);
			try {
				datagramSocket.receive(datagramPacket);
			} catch (IOException e) {
				e.printStackTrace();
			}

			data = datagramPacket.getData();
			int length = datagramPacket.getLength();
			String message = new String(data,0,length);
			send(message, UDP_CHATPORT+1);//for GKJ同時起動
			if (message.equals("exit")) System.exit(0);
			String[] mes = message.split(" ");
			if (mes.length==2){
				int penid = Integer.parseInt(mes[0]);
				if (mes[1].equals("atn")){
					satn.openingLecture.loadPenData(satn, satn.mysqldb);
					if (satn.notes.get(penid)==null) return; //筆記がない場合．たとえば送信チェックボックスだけ
					satn.notes.get(penid).numPT.animateToColor(Color.yellow, 0);
					satn.notes.get(penid).numPT.animateToColor(Color.white, 3000);
				}
			} else {
//				JOptionPane.showConfirmDialog(satn, message);
				System.out.println(message);
			}
		}
	}
	
	private DatagramSocket recoverAfterPreviousShutdown() {
		send("exit");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket(UDP_CHATPORT);
		} catch (SocketException e) {
			e.printStackTrace();
			if (e instanceof BindException){
				datagramSocket = recoverAfterPreviousShutdown();
			}
		}
		return datagramSocket;
	}
	public void send(String mes){
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		//		lastURL = url; これをやると，メニューに追加もされない
		byte[] mesdata = mes.getBytes();
		InetAddress host = null;
		try {
			host = InetAddress.getByName("127.0.0.1");
//			host = InetAddress.getByName("255.255.255.255");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		DatagramPacket datagramPacket = new DatagramPacket(mesdata,mesdata.length,host, UDP_CHATPORT);
		try {
			datagramSocket.send(datagramPacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void send(String mes, int portnum){
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		//		lastURL = url; これをやると，メニューに追加もされない
		byte[] mesdata = mes.getBytes();
		InetAddress host = null;
		try {
			host = InetAddress.getByName("127.0.0.1");
//			host = InetAddress.getByName("255.255.255.255");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		DatagramPacket datagramPacket = new DatagramPacket(mesdata,mesdata.length,host, portnum);
		try {
			datagramSocket.send(datagramPacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
