package ru.bitel.bgbilling.modules.inet.dyn.device.manad;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Utils;
import ru.bitel.oss.systems.inventory.resource.common.bean.Device;
import ru.bitel.oss.systems.inventory.resource.common.bean.DeviceType;
import ru.bitel.oss.systems.inventory.resource.common.dm.DeviceManager;
import ru.bitel.oss.systems.inventory.resource.common.dm.DeviceManagerAdapter;

public class ManadDeviceManager
	extends DeviceManagerAdapter
	implements DeviceManager
{
	private static Logger logger = LogManager.getLogger();
	
	private String host;
	private int port;
	
	private Socket socket;
	private PrintWriter out;
	
	private BufferedReader in;
	
	@Override
	public Object init( Setup setup, int moduleId,  Device<?, ?> device, DeviceType deviceType, ParameterMap parameterMap )
		throws Exception
	{
		List<InetSocketAddress> hosts = device.getHosts();
		
		InetSocketAddress socketAddress = hosts.get( 0 );
		host = socketAddress.getAddress().getHostAddress();
		port = socketAddress.getPort();
 		
		return null;
	}
	
	@Override
	public Object connect()
		throws Exception
	{
		socket = new Socket( host, port );
		out = new PrintWriter( socket.getOutputStream(), true );
		InputStreamReader isr = new InputStreamReader( socket.getInputStream() );
        in = new BufferedReader( isr );

		
		logger.info( "Connected" );
		
		return super.connect();
	}
	
	@Override
	public Object disconnect()
		throws Exception
	{
		super.disconnect();
		out.close();
		socket.close();
		in.close();
		out = null;		
		socket = null;
		in = null;

		logger.info( "Disconnected" );
		return null;
	}


		
	@Override
	public Object destroy()
		throws Exception
	{
		if( out != null )
		{
			out.close();
			out = null;
		}
		if( in != null )
		{
			in.close();
			in = null;
		}

		if( socket != null )
		{
			socket.close();
			socket = null;
		}

		return null;
	}

	

	@Override
	public Object uptime()
		throws Exception
	{
        out.println( "uptime" );
        String uptimeStr = in.readLine();
        return Utils.parseLong( uptimeStr, 0  );
	}

	

}
