// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2008, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.smslib.modem;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.smslib.GatewayException;

class IPModemDriver extends AModemDriver
{
	private String ipAddress;

	private int ipPort;

	TelnetClient tc;

	private InputStream in;

	private OutputStream out;

	private Peeker peeker;

	TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);

	EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);

	SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

	IPModemDriver(ModemGateway myGateway, String deviceParms)
	{
		super(myGateway, deviceParms);
		StringTokenizer tokens = new StringTokenizer(deviceParms, ":");
		this.ipAddress = tokens.nextToken();
		this.ipPort = Integer.parseInt(tokens.nextToken());
		this.tc = null;
	}

	@SuppressWarnings("unused")
	@Override
	void connectPort() throws GatewayException, IOException, InterruptedException
	{
		try
		{
			this.gateway.getService().getLogger().logInfo("Opening: " +this. ipAddress + " @" + this.ipPort, null, getGateway().getGatewayId());
			this.tc = new TelnetClient();
			this.tc.addOptionHandler(this.ttopt);
			this.tc.addOptionHandler(this.echoopt);
			this.tc.addOptionHandler(this.gaopt);
			this.tc.connect(this.ipAddress, this.ipPort);
			this.in = this.tc.getInputStream();
			this.out = this.tc.getOutputStream();
			this.peeker = new Peeker();
		}
		catch (InvalidTelnetOptionException e)
		{
			throw new GatewayException("Unsupported telnet option for the selected IP connection.");
		}
	}

	@Override
	void disconnectPort() throws IOException, InterruptedException
	{
		this.gateway.getService().getLogger().logInfo("Closing: " + this.ipAddress + " @" + this.ipPort, null, getGateway().getGatewayId());
		synchronized (this.SYNC_Reader)
		{
			if (this.tc != null) this.tc.disconnect();
			this.tc = null;
			this.peeker.interrupt();
			this.peeker.join();
		}
	}

	@Override
	void clear() throws IOException
	{
		while (portHasData())
			read();
	}

	@Override
	boolean portHasData() throws IOException
	{
		return (this.in.available() > 0);
	}

	@Override
	public void write(char c) throws IOException
	{
		this.out.write((short) c);
		this.out.flush();
	}

	@Override
	public void write(byte[] s) throws IOException
	{
		this.out.write(s);
		this.out.flush();
	}

	@Override
	int read() throws IOException
	{
		return this.in.read();
	}

	private class Peeker extends Thread
	{
		public Peeker()
		{
			setPriority(MIN_PRIORITY);
			start();
		}

		@Override
		public void run()
		{
			IPModemDriver.this.gateway.getService().getLogger().logDebug("Peeker started.", null, getGateway().getGatewayId());
			while (true)
			{
				try
				{
					if (IPModemDriver.this.tc != null)
					{
						if (portHasData())
						{
							synchronized (IPModemDriver.this.SYNC_Reader)
							{
								IPModemDriver.this.dataReceived = true;
								IPModemDriver.this.SYNC_Reader.notifyAll();
							}
						}
					}
					sleep(IPModemDriver.this.gateway.getService().S.SERIAL_POLLING_INTERVAL);
				}
				catch (InterruptedException e)
				{
					if (IPModemDriver.this.tc == null) break;
				}
				catch (IOException e)
				{
					// Swallow this...
				}
			}
			IPModemDriver.this.gateway.getService().getLogger().logDebug("Peeker stopped.", null, getGateway().getGatewayId());
		}
	}
}
