package org.kne.cloud.network.tun;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.List;

import one.papachi.tuntap4j.TunDevice;

public class LinuxTUNNetworkDevice extends TUNNetworkDevice {
	private TunDevice tun;
	private String name;
	public LinuxTUNNetworkDevice(String name, String type) throws IOException {
		this.name=name;
		tun=new TunDevice(name);
		tun.open();
	}

	@Override
	public boolean isOpen() {
		try {
			return tun.isOpen();
		} catch (IOException e) {
			try {
				tun.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public void close() throws IOException {
		if(channel!=null&&channel.isOpen()) {
			channel.close();
			channel=null;
		}
		TunDevice tund=tun;
		tun=null;
		if(tund!=null)
		tund.close();
	}
	private LinuxTUNChannel channel;
	@Override
	public TUNChannel openSession() throws IOException {
		if(channel==null) {
		channel=new LinuxTUNChannel(tun);
		}
		return channel;
	}

	@Override
	public List<InetAddressRow> getIPAddress() throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setIPAddress(List<InetAddressRow> rows) throws IOException {
		// TODO Auto-generated method stub
		for(InetAddressRow row:rows) {
		try {
			Process proc=Runtime.getRuntime().exec(new String[] {"ip","addr","add",row.getAddress().getHostAddress()+"/"+row.getPerfix(),"dev",name});
			Thread t=new Thread(()->{
				BufferedReader br=new BufferedReader(proc.errorReader());
				String str=null;
				try {
					while((str=br.readLine())!=null) {
						System.out.println(str);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			t.start();
			int rez=proc.waitFor();
			if(rez!=0) {
				throw new SocketException("set address failed!");
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		}
	}

	@Override
	public int getMTU() throws IOException {
		return tun.getMTU();
	}

	@Override
	public void setMTU(int mtu) throws IOException {
		tun.setMTU(mtu);
	}

	@Override
	public void setDNSAddress(List<InetAddress> address) throws IOException {
		// TODO Auto-generated method stub

	}

	@Override
	public List<InetAddress> getDNSAddress() throws SocketException {
		// TODO Auto-generated method stub
		return null;
	}

}
