public EditGateUser(GerenciarPortoesViewModel viewModel, GateDevices gateKey)
        {
            _viewModel = viewModel;
            Grid grid = new Grid();
            this.gateKey = gateKey;
            string name = gateKey.SKeyName;
            if (name.Length <= 4)
                name = gateKey.SkeyBleId;

            Title = "Editar " + name;

            removerUserGate.AnimateWithAction();
            removerUserGate.Clicked += removerUserGate_Clicked;


            grid.Children.AddVertical(listProfileDisponiveis);
            grid.Children.Add(removerUserGate);

            listProfileDisponiveis.ItemTapped += listProfileDisponiveis_ItemTapped;

            var absoluteLayout = new AbsoluteLayout();
            var background = new Image
            {
                Style = Styles.BackgroundImage
            };

            absoluteLayout.Children.Add(background, new Rectangle(0, 0, 1, 1), AbsoluteLayoutFlags.All);
            absoluteLayout.Children.Add(grid, new Rectangle(0, 0, 1, 1), AbsoluteLayoutFlags.All);

            Content = absoluteLayout;
        }
        public bool Equals(GateDevices other)
        {
            if (other == null)
                return false;

            //Usado para edicao de descricao de portao nao gerenciado
            if (!string.IsNullOrEmpty (GateLicId) && !string.IsNullOrEmpty (other.GateLicId))
                return ((GateLicId).Equals (other.GateLicId));

            //Usado para verificacao se novo user de portao jah esta cadastrado
            if (!string.IsNullOrEmpty (Email) && !string.IsNullOrEmpty (other.Email))
                return ((GateLicId).Equals (other.GateLicId));

            return false;
        }
		public async Task<GateDevices> newGateSkeyUser()
		{
			var gateDevices = new Repository<GateDevices>();
			if (App.gateSkey != null && !gateDevices.GetAllAsync().Result.Any(sk => sk.SkeyBleId == App.gateSkey.deviceAddress))
			{
				var gateUser = new GateDevices();
				gateUser.Id = Guid.NewGuid().ToString();
				gateUser.SkeyBleId = App.gateSkey.deviceAddress;
				gateUser.SKeyName = App.gateSkey.deviceName;
				gateUser.GateLicId = SelectedGate.Id;
				gateUser.Perfil = "Liberado Geral";
				gateUsers.Add(gateUser);
				App.gateSkeys.Add(App.gateSkey);
				App.gateSkey = null;
				Console.WriteLine("Novo gate device  sKey:" + App.gateSkey);
				await tableDevices.CreateAsync(gateUser);
				return gateUser;
			}
			return null;
		}
		private async void newGateUserCell(string email)
		{
			var gateUser = new GateDevices(email, true);
			if (gateUsers.Contains(gateUser))
			{
				IsBusy = false;
				await notificator.Notify(ToastNotificationType.Error, "MySafety", "Usuario já tem acesso a esse portao", TimeSpan.FromSeconds(3));
				return;
			}

			IsBusy = true;
			var novoUser = new Repository<MysafetyUser>().GetAllAsync().Result.Single(us => us.Email == email);
			if (novoUser == null)
			{
				await notificator.Notify(ToastNotificationType.Error, "MySafety", "Usuario não cadastrado no sistema", TimeSpan.FromSeconds(3));

				//TODO perguntar se deseja enviar convite com link para instalacao do app


				IsBusy = false;
				return;
			}
			IsBusy = false;

			gateUser.Id = novoUser.Id + "_" + SelectedGate.Id;  
			gateUser.Name = novoUser.Nome;
			gateUser.SkeyBleId = novoUser.mySKeyId;
			gateUser.PhoneBleId = novoUser.BleIdCel;
			gateUser.SKeyName = novoUser.mySKeyName;
			gateUser.GateLicId = SelectedGate.Id;
			gateUser.GateBleId = SelectedGate.BleId;
			gateUser.Perfil = "Liberado Geral";
			gateUser.GateDescr = "Portao de " + Settings.nome;
			gateUser.Code = MySafetyDll.MySafety.calculateAccessCode(SelectedGate.BleId, novoUser.BleIdCel,((App)Application.Current).mysafetyDll.localBleAddress);
			gateUsers.Add(gateUser);
			if (!string.IsNullOrEmpty(gateUser.SkeyBleId) && !gateUser.SkeyBleId.Equals("00:00:00:00:00:00"))
			{
				BleDevice naLista = new BleDevice(gateUser.SkeyBleId, gateUser.SKeyName);
				naLista.selecionado = true;   //impede ser mostrado poder ser selecionado em Find
				App.gateSkeys.Add(naLista);
			}
			await(tableDevices.CreateAsync(gateUser));
			Console.WriteLine("Novo gate device  fone:" + gateUser.Name);
		}
		public async void removeGateDevice(GateDevices gateUser)
		{
			gateUsers.Remove(gateUser);
			Console.WriteLine("Removendo user de portao:" + gateUser.labelName + "   " + gateUser.Email + " " + gateUser.SkeyBleId);
			await tableDevices.RemoveAsync(gateUser);
		}
		/// <summary>
		/// Alteracao de nome e descricao de portao
		/// </summary>
		async public void Save()
		{
			Debug.WriteLine("Salvando alteracao de nome/descricao de portao");
			if (SelectedGate.IsOwned)  //Portao gerenciado
				await new Repository<Gates>().UpdateAsync(SelectedGate);
			else
			{       //Portao apenas acessivel, apenas alteracao de descricao do GateDevices
				GateDevices gt = new GateDevices(SelectedGate.Id);
				int pos;
				if ((pos=App.PortoesNaogerenciados.IndexOf(gt)) >=0)
				{
					gt = App.PortoesNaogerenciados[pos];
					gt.GateDescr = SelectedGate.Name;
					await tableDevices.UpdateAsync(gt);
				}
			}
		}
		async void completaListaProtegidos ()
		{
			//Acessa contatos para obter nome e fone do protegido
			GateDevices contato; // apenas usado para armazenar os dados a extrair dos contatos
			ObservableCollection<GateDevices> contatos = new ObservableCollection<GateDevices> ();
			if (await CrossContacts.Current.RequestPermission ()) {
				CrossContacts.Current.PreferContactAggregation = false;//recommended

				ObservableCollection<Contact> ContactsItemSource = new ObservableCollection<Contact> (CrossContacts.Current.Contacts.ToList ());
				string email = null;
				foreach (var item in ContactsItemSource) {
					foreach (var em in item.Emails)
						if (!string.IsNullOrEmpty (em.Address) && em.Address.Count () > 4) {
							email = em.Address;
							break;
						}

					if (string.IsNullOrEmpty (email)) {
						contato = new GateDevices ();
//						contato.GateLicId //Licenca do gerenciador do portao = email;   //para poder usar IndexOf()
						contato.Name = item.FirstName + " " + item.LastName;

						foreach (var fone in item.Phones)
							if (!string.IsNullOrEmpty (fone.Number) && fone.Number.Count () > 4) {
								contato.PhoneBleId = fone.Number;
								break;
							}
						contatos.Add (contato);
					}
				}            
			}

//			int pos;
			foreach (var panicContact in protegidos) {
				panicContact.IsProt = true;
				if (panicContact.Estado == 'S') {
					panicContact.Estado = 'C';  //Valida cadastro de protegido
					panicContact.ProtUserId = Settings.user_Id; //No momento que o protejido cadastrou, nao tinha como saber...
					await PanicContactRp.UpdateAsync (panicContact);
				}

				//Obtem nome e fone dos contatos, apenas para mostrar na lista de protejidos
				contato = new GateDevices ();
//				contato.        public string GateLicId { get; set; } //Licenca do gerenciador do portao = panicContact.Email;
				if ((/*pos = */contatos.IndexOf (contato)) >= 0) {
					panicContact.Name = contato.Name;
					panicContact.phoneNumber = contato.PhoneBleId;
				}

			}
		}