package jp.hasc.hupserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

/*
 * HUPSimpleServer
 *   　　クライアント・サーバの接続アドレスは固定とする。
 *   
 */


public class HUPSimpleServer implements Runnable{
	static final int BufSize = 1024;

	int serverPort_;
	int dataPort_;

	DatagramSocket serverSoc_;
	byte[] buf_;
	byte[] buf2_;
	boolean loopFlag_;

//	InetAddress dstAddr_;
	DatagramSocket sSock_; // server socket

	DatagramSocket ds_; // client(ipod socket)
	DatagramPacket dp_;
	
	HUPMaster hupm_;
	int id_;
	
	HUPSimpleServer(int port1, int port2, HUPMaster hm, int id){
		id_ = id;
		hupm_ = hm;
		serverPort_ = port1;
		dataPort_ = port2;
		buf_ = new byte[BufSize];	
		buf2_ = new byte[BufSize];
		loopFlag_ = true;
	}
	
	public void startServer(){
		try {
			serverSoc_ = new DatagramSocket(serverPort_);
//			System.out.println("Binding Socket on port:"+serverPort_);
			hupm_.logln("Binding Socket on port:"+serverPort_);
			
		} catch (SocketException e) {
			hupm_.logln("Can't open UDP socket on port "+serverPort_);
			e.printStackTrace();
			System.exit(1);
		}
	}
	public void stopServer(){
		loopFlag_ = false;
		serverSoc_.close();
	}
	
	@Override
	public void run() {
		InetAddress cAddr;
		int cPort;
		this.startServer();
		DatagramPacket rcvPacket = new DatagramPacket(buf_, BufSize);
		DatagramPacket sndPacket;
		hupm_.logln("Waiting connection.."+serverSoc_.getLocalAddress()+":"+serverSoc_.getLocalPort());
		while(loopFlag_){			
			try {
				serverSoc_.receive(rcvPacket);
				
	            cAddr = rcvPacket.getAddress();
	            cPort = rcvPacket.getPort();
	            
				ds_ = new DatagramSocket(dataPort_);
        		String str = "#PortInfo "+dataPort_+"\n";
        		byte[] bts = str.getBytes();

        		sndPacket = new DatagramPacket(bts,bts.length);
        		sndPacket.setAddress(cAddr);
        		sndPacket.setPort(cPort);
        		serverSoc_.send(sndPacket);
				
	    		dp_ = new DatagramPacket(buf2_,BufSize);
	    		
	    		hupm_.logln("Now Waiting for "+ds_.getLocalAddress()+":"+ds_.getLocalPort());
	    		hupm_.logln("Transfer for "+cAddr+":"+cPort);
    			try {
    				while (loopFlag_){
	    				ds_.receive(dp_); // 受け取ったパケットを
//	    				System.out.println("get packet"+dp_.getAddress()+":"+dp_.getPort());
	    				dp_.setAddress(cAddr);
	    				dp_.setPort(cPort);
//	    				sSock_.send(dp_); // サーバソケットで送信
	    				serverSoc_.send(dp_); 
	    				hupm_.countUp(id_,dp_.getLength());
    				}
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    				hupm_.logln("Err on innerLoop for"+cAddr+":"+cPort);
    			}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
	}

}
