// ChmodDialog.cs
//
//  Copyright (C) 2008-2009 Christian Eide
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
using System;

namespace bareFTP.Gui.Dialog
{
	
	public partial class ChmodDialog : Gtk.Dialog
	{
		
		public ChmodDialog()
		{
			this.Build();
		}
		
		public string Permissions
		{
			get {
				
				byte u = 0;
				byte g = 0;
				byte o = 0;
				
				if(ur.Active)
					u = Convert.ToByte(u | Convert.ToByte(4));
				if(uw.Active)
					u = Convert.ToByte(u | Convert.ToByte(2));
				if(ux.Active)
					u = Convert.ToByte(u | Convert.ToByte(1));
				
				if(gr.Active)
					g = Convert.ToByte(g | Convert.ToByte(4));
				if(gw.Active)
					g = Convert.ToByte(g | Convert.ToByte(2));
				if(gx.Active)
					g = Convert.ToByte(g | Convert.ToByte(1));
				
				if(or.Active)
					o = Convert.ToByte(o | Convert.ToByte(4));
				if(ow.Active)
					o = Convert.ToByte(o | Convert.ToByte(2));
				if(ox.Active)
					o = Convert.ToByte(o | Convert.ToByte(1));
				
				return Convert.ToInt32(u).ToString() + Convert.ToInt32(g).ToString() + Convert.ToInt32(o).ToString();

			}

			set
			{
				string perm = value;
				
				if(!string.IsNullOrEmpty(perm))
				{
					if(perm.Length > 9)
						perm = perm.Remove(0,1);
					
					if(perm.Length != 9)
					{
						Console.WriteLine("Couldn't parse permissions: " + perm);
						return;
					}
						
					
					string us = perm.Substring(0,3);
					string gs = perm.Substring(3,3);
					string os = perm.Substring(6,3);
					
					if(us.IndexOf("r") >= 0)
						ur.Active = true;
					if(us.IndexOf("w") >= 0)
						uw.Active = true;
					if(us.IndexOf("x") >= 0)
						ux.Active = true;
			
					if(gs.IndexOf("r") >= 0)
						gr.Active = true;
					if(gs.IndexOf("w") >= 0)
						gw.Active = true;
					if(gs.IndexOf("x") >= 0)
						gx.Active = true;
			
					if(os.IndexOf("r") >= 0)
						or.Active = true;
					if(os.IndexOf("w") >= 0)
						ow.Active = true;
					if(os.IndexOf("x") >= 0)
						ox.Active = true;
				}
			}
		}
	}
}
