using System;

namespace DotNetMock.Examples.Mainframe
{
	public class CustomerNumberCollector
	{
		private IMainframeConnection _connection = null;
		private string _name = "";
		private string _userName = "";
		private string _password = "";

		public CustomerNumberCollector(IMainframeConnection connection)
		{
			_connection = connection;	
		}

		public void CollectCustomerInformation(string customerNumber) 
		{
			_connection.Connect("A");
			_connection.SetScreen("MainMenu");
			_connection.SetScreen("CustomerInformation");
			_connection.PutField(23, 50, customerNumber, customerNumber.Length);
			_connection.SendKey(MainframeConnection.Keys.Enter);
			string errorMessage = _connection.GetField(23, 2, 25);
			
			if (errorMessage.Equals("CUSTOMER NUMBER NOT FOUND")) 
			{
				_connection.Disconnect();
				throw new ApplicationException("Customer Number could not be found");
			}
			this.Name = _connection.GetField(20, 4, 25);
			this.UserName = _connection.GetField(21, 4, 8);
			this.Password = _connection.GetField(22, 4, 8);

			_connection.Disconnect();
		}
		public void UpdateInformation(string customerNumber, string name, string userName, string password) 
		{
			_connection.Connect("A");
			_connection.SetScreen("MainMenu");
			_connection.SetScreen("CustomerInformation");
			_connection.PutField(23, 50, customerNumber, customerNumber.Length);
			_connection.SendKey(MainframeConnection.Keys.Enter);
			string errorMessage = _connection.GetField(23, 2, 25);
			if (errorMessage.Equals("CUSTOMER NUMBER NOT FOUND")) 
			{
				_connection.Disconnect();
				throw new ApplicationException("Customer Number could not be found");
			}
			_connection.PutField(20, 4, name, name.Length);
			_connection.PutField(21, 4, userName, userName.Length);
			_connection.PutField(22, 4, password, password.Length);
			_connection.SendKey(MainframeConnection.Keys.Enter);

			errorMessage = _connection.GetField(23, 2, 25);
			if (errorMessage.Equals("TRANSACTION FAILED"))
			{
				_connection.Disconnect();
				throw new ApplicationException("Customer Information update failed.");
			}

			this.Name = _connection.GetField(20, 4, 25);
			this.UserName = _connection.GetField(21, 4, 8);
			this.Password = _connection.GetField(22, 4, 8);
		}
		public string Name 
		{
			get { return _name.Trim(); }
			set { _name = value; }
		}
		public string UserName 
		{
			get { return _userName.Trim(); }
			set { _userName = value; }
		}
		public string Password
		{
			get { return _password.Trim(); }
			set { _password = value; }
		}
	}
}
