// This class is based on PseudoTerminal.cs from pty-sharp
//
// Original copyright notice:
// Author: Miguel de Icaza (miguel@gnome.org)
// Copyright 2009, Novell, Inc.
// Original license: MIT X11
//
//
// Modified and extended for bareFTP by Christian Eide <christian@eide-itc.no>


using System;
using System.Runtime.InteropServices;

namespace bareFTP.SftpPty {

	public class PseudoTerminal : IDisposable {
		
		[DllImport ("libsftppty.so")]
		extern static int _pty_sharp_open (out int pid_t_child,
						 out int slave_fd,
						 string [] env_add,
						 string command,
						 string [] argv,
						 string directory);

		[DllImport ("libsftppty.so")]
		extern static void _pty_sharp_set_utf8 (int pty, int utf8);
		
		[DllImport ("libsftppty.so")]
		extern static int _bareftp_get_ready_fd (int fd_console, int fd_data, bool retry);

		int fd;
		int child_pid;
		int slave_fd;

		public int ChildPid {
			get { return child_pid; }
		}

		public int FileDescriptor {
			get { return fd; }
		}
		
		public int SlaveFileDescriptor
		{
			get { return slave_fd; }
		}
			
		internal PseudoTerminal (int fd, int child_pid, int slave_fd)
		{
			this.fd = fd;
			this.child_pid = child_pid;
			this.slave_fd = slave_fd;
		}

		public static PseudoTerminal Open (string [] env_add, string command, string [] argv, string dir)
		{
			int child_pid, fd;
			int slave_fd;

			fd = _pty_sharp_open (out child_pid, out slave_fd, env_add, command, argv, dir);
			if (fd == -1)
				return null;

			return new PseudoTerminal (fd, child_pid, slave_fd);
		}


		public void SetUTF8 (bool status)
		{
			_pty_sharp_set_utf8 (fd, status ? 1 : 0);
		}
		
		public int GetReadyFileDescriptor(int fd_data, int fd_console, bool retry)
		{
			return 	_bareftp_get_ready_fd (fd_data, fd_console, retry);
		}

		public void Dispose()
		{
			Dispose(true);

			GC.SuppressFinalize(this);
		}
		
		protected virtual void Dispose (bool disposing)
		{
			if (fd == -1)
				return;
			fd = -1;
		}

		~PseudoTerminal ()
		{
			Dispose (false);
		}
	}
}
