public void LoginWithApi(ApiEw ew)
        {
            var request = new RestRequest("earthwatchers/loginwithapi", Method.POST) { RequestFormat = DataFormat.Json };
            request.JsonSerializer = new JsonSerializer();
            request.AddBody(ew);

            client.ExecuteAsync<Earthwatcher>(request, response =>
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                        ApiEwReceived(
                            response.Data, null)
                    ));
        }
        public Startup(IDictionary<string,string> initParams)
        {
            InitializeComponent();

            if (initParams.ContainsKey("authtoken"))
            {
                string[] authtoken = initParams["authtoken"].Split(':');
                if (authtoken[0] == "true")
                {
                    EarthwatcherRequests earthwatcherRequest = new EarthwatcherRequests(new Uri(Application.Current.Host.Source, "/api").ToString());
                    earthwatcherRequest.EarthwatcherReceived += earthwatcherRequest_EarthwatcherReceived;
                    earthwatcherRequest.GetLogged();
                }
            }
            else
                if (initParams.ContainsKey("api"))
                {
                    ApiEw ew = new ApiEw();

                    ew.Api = initParams["api"];
                    ew.UserId = initParams["userId"];
                    ew.NickName = initParams["nickName"];
                    ew.AccessToken = initParams["accessToken"];
                    if (initParams.ContainsKey("secretToken"))
                            ew.SecretToken = initParams["secretToken"];

                    EarthwatcherRequests earthwatcherRequest = new EarthwatcherRequests(new Uri(Application.Current.Host.Source, "/api").ToString());
                    earthwatcherRequest.LoginWithApi(ew);
                    earthwatcherRequest.ApiEwReceived += earthwatcherRequest_ApiEwReceived;
                }
            if (initParams.ContainsKey("credentials"))
                {
                    string[] credentials = initParams["credentials"].Split(':');
                    if (credentials.Length >= 2 && !string.IsNullOrEmpty(credentials[0]) && !string.IsNullOrEmpty(credentials[1]))
                    {
                        geohexcode = credentials[2].Trim();

                        EarthwatcherRequests earthwatcherRequest = new EarthwatcherRequests(new Uri(Application.Current.Host.Source, "/api").ToString());
                        earthwatcherRequest.EarthwatcherReceived += earthwatcherRequest_EarthwatcherReceived;
                        password = credentials[1].Trim();
                        earthwatcherRequest.GetByName(credentials[0].Trim(), password);
                    }
                    else
                    {
                        Earthwatchers.UI.App.BackToLoginPage();
                    }
                }
        }
 public ApiEw CreateApiEwLogin(ApiEw ew)  //Inserta el registro en la tabla ApiEwLogin
 {
     connection.Open();
     var cmd = connection.CreateCommand() as SqlCommand;
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.CommandText = "Earthwatcher_CreateApiEwLogin";
     cmd.Parameters.Add(new SqlParameter("@Api", ew.Api));
     cmd.Parameters.Add(new SqlParameter("@UserId", ew.UserId));
     cmd.Parameters.Add(new SqlParameter("@NickName", ew.NickName));
     cmd.Parameters.Add(new SqlParameter("@SecretToken", ew.SecretToken));
     cmd.Parameters.Add(new SqlParameter("@AccessToken", ew.AccessToken));
     cmd.Parameters.Add(new SqlParameter("@Mail", ew.Mail));
     var idParameter = new SqlParameter("@ID", SqlDbType.Int) { Direction = ParameterDirection.Output };
     cmd.Parameters.Add(idParameter);
     cmd.ExecuteNonQuery();
     var id = (int)idParameter.Value;
     ew.Id = id;
     connection.Close();
     return ew;
 }
        public HttpResponseMessage<Earthwatcher> LoginWithApi(ApiEw ew, HttpRequestMessage<ApiEw> request)
        {
            var localization = new LocalizationService();
            string locale = localization.GetLocale();

            if(!string.IsNullOrEmpty(ew.UserId))
            {
                ApiEw apiEw = earthwatcherRepository.GetApiEw(ew.Api, ew.UserId);

                if (apiEw == null)  //Si no existe en la tabla ApiEwLogin lo inserta y ademas Crea el EARTHWATCHER
                {
                    //INSERTA EL ApiEw en la tabla ApiEwLogin
                    ApiEw newApiEw = earthwatcherRepository.CreateApiEwLogin(ew);

                    if(ew.Api == "Facebook")
                    {
                        Earthwatcher ewIdemFbMail = earthwatcherRepository.GetEarthwatcher(ew.Mail, false);

                        if(ewIdemFbMail != null)  //Si en FB tiene el mismo mail que en guardianes lo relaciona
                        {
                            //Relaciona al ApiEw de facebook con el Earthwatcher del mismo mail
                            earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, ewIdemFbMail.Id);

                            //Le pasa el UserId y AccessToken para conectarse
                            ewIdemFbMail.UserId = ew.UserId;
                            ewIdemFbMail.AccessToken = ew.AccessToken;

                            //Devuelve el Ew que YA EXISTE relacionado con ese mail de FB
                            return new HttpResponseMessage<Earthwatcher>(ewIdemFbMail) { StatusCode = HttpStatusCode.OK };
                        }
                        else
                        {
                            //INSERTA EL EARTHWATCHER
                            var earthwatcher = new Earthwatcher();
                            if(!string.IsNullOrEmpty(ew.Mail))
                            {
                                earthwatcher.Name = ew.Mail;   //Ingreso el mail valido de ese Ew
                            }
                            else
                            {
                                earthwatcher.Name = ew.NickName + ew.UserId.ToString();  //Ingreso un customMail para ese EW
                            }
                            earthwatcher.Password = ew.NickName + earthwatcher.NickName + ew.UserId.ToString(); //Pass = Doble nombre mas userId
                            earthwatcher.NickName = ew.NickName;
                            earthwatcher.Language = (locale != null) ? locale.Substring(0, 5) : "en-CA";
                            earthwatcher.Country = (locale != null) ? locale.Substring(3, 2) : "es-AR";
                            earthwatcher.PlayingRegion = (locale != null) ? Convert.ToInt32(locale.Substring(6, 1)) : 1;
                            earthwatcher.PlayingCountry = (regionRepository.GetById(earthwatcher.PlayingRegion)).CountryCode;
                            earthwatcher.Guid = Guid.NewGuid();

                            Earthwatcher newEarthwatcher = earthwatcherRepository.CreateEarthwatcher(earthwatcher);

                            //Relaciona al ApiEw con el Earthwatcher
                            earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, newEarthwatcher.Id);

                            //ASIGNO UNA LAND AL NUEVO EW
                            var newLand = earthwatcherRepository.AssignLandToEarthwatcher(earthwatcher.Id, string.Empty);
                            Land newLandObj = null;
                            Console.WriteLine("Me paso la new land " + newLand.Id + " " + newLand.LandId);
                            if (newLand == null) //Si la region esta completa le asigno la land del tutor
                            {
                                newLandObj = landRepository.GetTutorLand(earthwatcher.PlayingRegion);
                            }
                            if (newLandObj == null) //Si no esta completa la region
                            {
                                newLandObj = landRepository.GetLandByGeoHexKey(newLand.GeohexKey);
                            }
                            earthwatcher.Lands = new List<Land>();
                            earthwatcher.Lands.Add(newLandObj);
                            //Comunico a los usuarios conectados si es que la nueva land es de un usuario existente
                            NotificateUsers(newLand, earthwatcher.Id);

                            //Le pasa el D:\Dev\Greenpeace\Guardianes\Earthwatchers.UI\Requests\OpengeocoderRequests.csUserId y AccessToken para conectarse
                            newEarthwatcher.UserId = ew.UserId;
                            newEarthwatcher.AccessToken = ew.AccessToken;

                            //Devuelve el ew NUEVO relacionado con esa nueva cuenta de FB
                            return new HttpResponseMessage<Earthwatcher>(newEarthwatcher) { StatusCode = HttpStatusCode.OK };
                        }

                    }
                    if (ew.Api != "Facebook")
                    {
                        //INSERTA EL EARTHWATCHER
                        var earthwatcher = new Earthwatcher();
                        earthwatcher.Name = ew.NickName + ew.UserId.ToString();
                        earthwatcher.Password = ew.NickName + earthwatcher.NickName + ew.UserId.ToString(); //Pass = Doble nombre mas userId
                        earthwatcher.NickName = ew.NickName;
                        earthwatcher.Language = (locale != null) ? locale.Substring(0, 5) : "en-CA";
                        earthwatcher.Country = (locale != null) ? locale.Substring(3, 2) : "es-AR";
                        earthwatcher.PlayingRegion = (locale != null) ? Convert.ToInt32(locale.Substring(6, 1)) : 1;
                        earthwatcher.PlayingCountry = (regionRepository.GetById(earthwatcher.PlayingRegion)).CountryCode;
                        earthwatcher.Guid = Guid.NewGuid();

                        Earthwatcher newEarthwatcher = earthwatcherRepository.CreateEarthwatcher(earthwatcher);

                        //Relaciona al ApiEw con el Earthwatcher
                        earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, newEarthwatcher.Id);

                        var newLand = earthwatcherRepository.AssignLandToEarthwatcher(earthwatcher.Id, string.Empty);
                        Land newLandObj = null;
                        Console.WriteLine("Me paso la new land " + newLand.Id + " " + newLand.LandId);
                        if (newLand == null) //Si la region esta completa le asigno la land del tutor
                        {
                            newLandObj = landRepository.GetTutorLand(earthwatcher.PlayingRegion);
                        }
                        if (newLandObj == null) //Si no esta completa la region
                        {
                            newLandObj = landRepository.GetLandByGeoHexKey(newLand.GeohexKey);
                        }
                        earthwatcher.Lands = new List<Land>();
                        earthwatcher.Lands.Add(newLandObj);
                        //Comunico a los usuarios conectados si es que la nueva land es de un usuario existente
                        NotificateUsers(newLand, earthwatcher.Id);

                        //Le pasa el UserId y AccessToken para conectarse
                        newEarthwatcher.UserId = ew.UserId;
                        newEarthwatcher.AccessToken = ew.AccessToken;

                        return new HttpResponseMessage<Earthwatcher>(newEarthwatcher) { StatusCode = HttpStatusCode.OK };
                    }
                }
                else
                {
                    //Si ya existe en mi tabla ApiLogin Le updateo el accessToken
                    if(ew.AccessToken != apiEw.AccessToken)
                    {
                        earthwatcherRepository.UpdateAccessToken(apiEw.Id, ew.AccessToken);
                    }
                    //Lo busco por el Id del EW relacionado
                    Earthwatcher earthwatcher = earthwatcherRepository.GetEarthwatcher(apiEw.EarthwatcherId);

                    //Le Agrega el UserId al Earthwatcher y lo devuelve
                    earthwatcher.UserId = apiEw.UserId;
                    earthwatcher.AccessToken = ew.AccessToken;
                    return new HttpResponseMessage<Earthwatcher>(earthwatcher) { StatusCode = HttpStatusCode.OK };
                }
            }
            return new HttpResponseMessage<Earthwatcher>(null) { StatusCode = HttpStatusCode.BadRequest };
        }
        public HttpResponseMessage<Earthwatcher> LoginWithApi(ApiEw ew, HttpRequestMessage<ApiEw> request)
        {
            //ApiEw ew = prueba;
            if(!string.IsNullOrEmpty(ew.UserId))
            {
                ApiEw apiEw = earthwatcherRepository.GetApiEw(ew.Api, ew.UserId);

                if (apiEw == null)  //Si no existe en la tabla ApiEwLogin lo inserta y ademas Crea el EARTHWATCHER
                {
                    //INSERTA EL ApiEw en la tabla ApiEwLogin
                    ApiEw newApiEw = earthwatcherRepository.CreateApiEwLogin(ew);

                    if(ew.Api == "Facebook")
                    {
                        Earthwatcher ewIdemFbMail = earthwatcherRepository.GetEarthwatcher(ew.Mail, false);
                       
                        if(ewIdemFbMail != null)  //Si en FB tiene el mismo mail que en guardianes lo relaciona
                        {
                            //Relaciona al ApiEw de facebook con el Earthwatcher del mismo mail
                            earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, ewIdemFbMail.Id);

                            //Le pasa el UserId y AccessToken para conectarse
                            ewIdemFbMail.UserId = ew.UserId;
                            ewIdemFbMail.AccessToken = ew.AccessToken;

                            //Devuelve el Ew que YA EXISTE relacionado con ese mail de FB
                            return new HttpResponseMessage<Earthwatcher>(ewIdemFbMail) { StatusCode = HttpStatusCode.OK };                        
                        }
                        else
                        {
                            //INSERTA EL EARTHWATCHER
                            var earthwatcher = new Earthwatcher();
                            earthwatcher.Name = ew.Mail;   //Ingreso el mail valido de ese Ew
                            earthwatcher.NickName = ew.NickName;
                            earthwatcher.Language = "Spanish";
                            earthwatcher.Country = "Argentina";
                            earthwatcher.Guid = Guid.NewGuid();

                            Earthwatcher newEarthwatcher = earthwatcherRepository.CreateEarthwatcher(earthwatcher);

                            //Relaciona al ApiEw con el Earthwatcher
                            earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, newEarthwatcher.Id);

                            //ASIGNO UNA LAND AL NUEVO EW
                            string basecamp = System.Configuration.ConfigurationManager.AppSettings["Basecamp"];
                            var newLand = earthwatcherRepository.AssignLandToEarthwatcher(earthwatcher.Id, basecamp, string.Empty);
                            Console.WriteLine("Me paso la new land " + newLand.Id + " " + newLand.LandId);
                            if (newLand == null)
                            {
                                throw new HttpResponseException(string.Format("error: there is no free land available. basecamp: {0}, name: {1}", earthwatcher.Basecamp, earthwatcher.Name));
                            }
                            else
                            {
                                earthwatcher.Lands = new List<Land>();
                                earthwatcher.Lands.Add(landRepository.GetLand(newLand.Id));
                                //Comunico a los usuarios conectados si es que la nueva land es de un usuario existente
                                NotificateUsers(newLand, earthwatcher.Id);
                            }

                            //Le pasa el UserId y AccessToken para conectarse
                            newEarthwatcher.UserId = ew.UserId;
                            newEarthwatcher.AccessToken = ew.AccessToken;

                            //Devuelve el ew NUEVO relacionado con esa nueva cuenta de FB
                            return new HttpResponseMessage<Earthwatcher>(newEarthwatcher) { StatusCode = HttpStatusCode.OK };                        
                        }

                    }
                    if (ew.Api != "Facebook")
                    {
                        //INSERTA EL EARTHWATCHER
                        var earthwatcher = new Earthwatcher();
                        earthwatcher.Name = ew.UserId.ToString();   //????? no puede ir nulo, pongo el Id de usuario hasta que me ingrese un mail
                        earthwatcher.NickName = ew.NickName;
                        earthwatcher.Language = "Spanish";
                        earthwatcher.Country = "Argentina";
                        earthwatcher.Guid = Guid.NewGuid();

                        Earthwatcher newEarthwatcher = earthwatcherRepository.CreateEarthwatcher(earthwatcher);

                        //Relaciona al ApiEw con el Earthwatcher
                        earthwatcherRepository.LinkApiAndEarthwatcher(newApiEw.Id, newEarthwatcher.Id);

                        //ASIGNO UNA LAND AL NUEVO EW
                        string basecamp = System.Configuration.ConfigurationManager.AppSettings["Basecamp"];
                        var newLand = earthwatcherRepository.AssignLandToEarthwatcher(earthwatcher.Id, basecamp, string.Empty);
                        Console.WriteLine("Me paso la new land " + newLand.Id + " " + newLand.LandId);
                        if (newLand == null)
                        {
                            throw new HttpResponseException(string.Format("error: there is no free land available. basecamp: {0}, name: {1}", earthwatcher.Basecamp, earthwatcher.Name));
                        }
                        else
                        {
                            earthwatcher.Lands = new List<Land>();
                            earthwatcher.Lands.Add(landRepository.GetLand(newLand.Id));
                            //Comunico a los usuarios conectados si es que la nueva land es de un usuario existente
                            NotificateUsers(newLand, earthwatcher.Id);
                        }

                        //Le pasa el UserId y AccessToken para conectarse
                        newEarthwatcher.UserId = ew.UserId;
                        newEarthwatcher.AccessToken = ew.AccessToken;

                        return new HttpResponseMessage<Earthwatcher>(newEarthwatcher) { StatusCode = HttpStatusCode.OK };
                    }
                }
                else
                {
                    //Si ya existe en mi tabla ApiLogin Le updateo el accessToken
                    if(ew.AccessToken != apiEw.AccessToken)
                    {
                        earthwatcherRepository.UpdateAccessToken(apiEw.Id, ew.AccessToken);
                    }
                    //Lo busco por el Id del EW relacionado
                    Earthwatcher earthwatcher = earthwatcherRepository.GetEarthwatcher(apiEw.EarthwatcherId);
                    
                    //Le Agrega el UserId al Earthwatcher y lo devuelve
                    earthwatcher.UserId = apiEw.UserId;
                    earthwatcher.AccessToken = ew.AccessToken;
                    return new HttpResponseMessage<Earthwatcher>(earthwatcher) { StatusCode = HttpStatusCode.OK };
                }
            }
            return new HttpResponseMessage<Earthwatcher>(null) { StatusCode = HttpStatusCode.BadRequest };
        }