/// <summary>
        /// Add a seekios
        /// </summary>
        private async Task <bool> InsertSeekios(string seekiosName, string imei, string pin, byte[] seekiosPicture)
        {
            try
            {
                _dialogService.ShowLoadingLayout();
                var seekiosToAdd = new SeekiosDTO();
                seekiosToAdd.Imei           = imei;
                seekiosToAdd.SeekiosName    = seekiosName.ToUpperCaseFirst();
                seekiosToAdd.PinCode        = pin;
                seekiosToAdd.SeekiosPicture = seekiosPicture == null ? null : Convert.ToBase64String(seekiosPicture);
                // Add seekios in the database
                seekiosToAdd = await _dataService.InsertSeekios(seekiosToAdd);

                if (seekiosToAdd == null || seekiosToAdd.Idseekios <= 0)
                {
                    _dialogService.HideLoadingLayout();
                    return(false);
                }
                // Add seekios in local data
                App.CurrentUserEnvironment.LsSeekios.Add(seekiosToAdd);
                _dialogService.HideLoadingLayout();
                return(true);
            }
            catch (TimeoutException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (WebException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (Exception)
            {
                await _dialogService.ShowError(
                    Resources.UnexpectedError
                    , Resources.UnexpectedErrorTitle
                    , Resources.Close, null);
            }
            _dialogService.HideLoadingLayout();
            return(false);
        }
        /// <summary>
        /// Request battery level
        /// </summary>
        public async Task <bool> RequestBatteryLevel()
        {
            try
            {
                // If user has not enough credits, cancel the request
                int creditsDispo = 0;
                if (!int.TryParse(Helper.CreditHelper.TotalCredits, out creditsDispo))
                {
                    return(false);
                }
                if (creditsDispo <= 0)
                {
                    await _dialogService.ShowMessage(Resources.UserNoRequestLeft
                                                     , Resources.UserNoRequestLeftTitle);

                    return(false);
                }

                var seekios = App.CurrentUserEnvironment.LsSeekios.First(x => x.Idseekios == SeekiosSelected.Idseekios);
                // If the seekios is in power saving, cancel the request
                if (seekios.IsInPowerSaving == true)
                {
                    await _dialogService.ShowMessage(Resources.PowerSavingOn
                                                     , Resources.PowerSavingOnTitle
                                                     , Resources.PowerSavingTuto
                                                     , Resources.Close, (result) => { if (result)
                                                                                      {
                                                                                          App.Locator.Parameter.GoToTutorialPowerSaving();
                                                                                      }
                                                     });

                    return(false);
                }

                // Request on the webservice to update the battery level
                _dialogService.ShowLoadingLayout();
                if (await _dataService.RefreshSeekiosBatteryLevel(SeekiosSelected.Idseekios) != -1)
                {
                    seekios.HasGetLastInstruction             = false;
                    seekios.IsRefreshingBattery               = true;
                    App.Locator.DetailSeekios.SeekiosSelected = seekios;
                    _dialogService.HideLoadingLayout();
                    return(true);
                }
                _dialogService.HideLoadingLayout();
                return(false);
            }
            catch (TimeoutException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (WebException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (Exception)
            {
                await _dialogService.ShowError(
                    Resources.UnexpectedError
                    , Resources.UnexpectedErrorTitle
                    , Resources.Close, null);
            }
            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        ///  Update user
        /// </summary>
        public async Task <int> UpdateUser(string email, string phoneNumber, string firstName, string lastName)
        {
            try
            {
                // Check if internet is available
                if (!App.DeviceIsConnectedToInternet)
                {
                    await _dialogService.ShowMessage(Resources.WebErrorTitle, Resources.WebErrorButtonText);

                    return(-2);
                }

                // Update user data
                App.CurrentUserEnvironment.User.Email       = email;
                App.CurrentUserEnvironment.User.FirstName   = firstName.ToUpperCaseFirst();
                App.CurrentUserEnvironment.User.LastName    = lastName.ToUpperCaseFirst();
                App.CurrentUserEnvironment.User.UserPicture = UserPicture == null ? App.CurrentUserEnvironment.User.UserPicture : Convert.ToBase64String(UserPicture);

                // Show the loading layout
                _dialogService.ShowLoadingLayout();

                if (await _dataService.UpdateUser(App.CurrentUserEnvironment.User) == 1)
                {
                    // Hide the loading layout
                    _dialogService.HideLoadingLayout();
                    return(1);
                }
                else
                {
                    // Error message
                    await _dialogService.ShowMessage(Resources.UpdateUserFailedTitle, Resources.UpdateUserFailedContent);

                    // Hide the loading layout
                    _dialogService.HideLoadingLayout();
                    return(-1);
                }
            }
            catch (TimeoutException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (WebException)
            {
                await _dialogService.ShowError(
                    Resources.TimeoutError
                    , Resources.TimeoutErrorTitle
                    , Resources.Close, null);
            }
            catch (Exception)
            {
                await _dialogService.ShowError(
                    Resources.UnexpectedError
                    , Resources.UnexpectedErrorTitle
                    , Resources.Close, null);
            }
            _dialogService.HideLoadingLayout();
            return(-1);
        }
        /// <summary>
        /// Select a mode
        /// </summary>
        public async Task <bool> SelectMode(ModeDefinitionEnum modeDefinition)
        {
            try
            {
                // User is out of requests
                if (int.Parse(CreditHelper.TotalCredits) <= 0)
                {
                    await _dialogService.ShowMessage(Resources.UserNoRequestLeft
                                                     , Resources.UserNoRequestLeftTitle);

                    return(false);
                }

                // User has no internet
                if (!App.DeviceIsConnectedToInternet)
                {
                    await _dialogService.ShowMessage(Resources.NoInternetMessage
                                                     , Resources.NoInternetTitle);

                    return(false);
                }

                // If a mode is already active on the seekios, we display custom popup
                var modeActive = App.CurrentUserEnvironment.LsMode.FirstOrDefault(el => el.Seekios_idseekios == App.Locator.DetailSeekios.SeekiosSelected.Idseekios);
                if (modeActive != null)
                {
                    if (!await _dialogService.ShowChangeModePopup(Resources.ModeChangeTitle
                                                                  , Resources.ModeChangePowerSaving
                                                                  , modeActive.ModeDefinition_idmodeDefinition
                                                                  , (int)modeDefinition
                                                                  , SeekiosUpdated.IsInPowerSaving))
                    {
                        return(false);
                    }
                }

                // Display loading layout
                _dialogService.ShowLoadingLayout();

                // Settings to save offline the preferences for mode zone / don't move
                var trackingSetting = App.Locator.ModeSelection.LsTrackingSetting.FirstOrDefault(x => x.IdSeekios == App.Locator.DetailSeekios.SeekiosSelected.Idseekios && x.ModeDefinition == modeDefinition);
                if (trackingSetting == null)
                {
                    trackingSetting = new TrackingSetting()
                    {
                        IdSeekios      = SeekiosUpdated.Idseekios,
                        ModeDefinition = modeDefinition,
                        RefreshTime    = MapViewModelBase.RefreshTime,
                    };
                    App.Locator.ModeSelection.LsTrackingSetting.Add(trackingSetting);
                }
                else
                {
                    trackingSetting.RefreshTime = MapViewModelBase.RefreshTime;
                }

                // Create the new mode to add
                var modeToAddInDb = new ModeDTO
                {
                    Seekios_idseekios = SeekiosUpdated.Idseekios,
                    Trame             = string.Empty,
                    Device_iddevice   = App.CurrentUserEnvironment.Device != null ? App.CurrentUserEnvironment.Device.Iddevice : 0,
                };

                // Save the mode in database
                int idMode        = 0;
                var timeDiffHours = Math.Ceiling((DateTime.Now - DateTime.UtcNow).TotalHours);
                switch (modeDefinition)
                {
                case ModeDefinitionEnum.ModeDontMove:
                    trackingSetting.IsEnable             = App.Locator.ModeDontMove.IsTrackingSettingEnable;
                    trackingSetting.IsPowerSavingEnabled = App.Locator.ModeDontMove.IsPowerSavingEnabled;
                    modeToAddInDb.Trame = string.Format("{0};{1}", timeDiffHours, MapViewModelBase.RefreshTime == 0 ? string.Empty : MapViewModelBase.RefreshTime.ToString());
                    modeToAddInDb.IsPowerSavingEnabled = App.Locator.ModeDontMove.IsPowerSavingEnabled;
                    idMode = await _dataService.InsertModeDontMove(modeToAddInDb, App.Locator.ModeDontMove.LsAlertsModeDontMove);

                    break;

                case ModeDefinitionEnum.ModeZone:
                    trackingSetting.IsEnable             = App.Locator.ModeZone.IsTrackingSettingEnable;
                    trackingSetting.IsPowerSavingEnabled = App.Locator.ModeZone.IsPowerSavingEnabled;
                    modeToAddInDb.Trame = string.Format("{0};{1}", timeDiffHours, App.Locator.ModeZone.CodeTrame(App.Locator.ModeZone.LsAreaCoordsMap));
                    modeToAddInDb.IsPowerSavingEnabled = App.Locator.ModeZone.IsPowerSavingEnabled;
                    idMode = await _dataService.InsertModeZone(modeToAddInDb, App.Locator.ModeZone.LsAlertsModeZone);

                    break;

                case ModeDefinitionEnum.ModeTracking:
                    modeToAddInDb.Trame = string.Format("{0};{1}", timeDiffHours, MapViewModelBase.RefreshTime == 0 ? string.Empty : MapViewModelBase.RefreshTime.ToString());
                    modeToAddInDb.IsPowerSavingEnabled   = App.Locator.ModeTracking.IsPowerSavingEnabled;
                    trackingSetting.IsPowerSavingEnabled = App.Locator.ModeTracking.IsPowerSavingEnabled;
                    idMode = await _dataService.InsertModeTracking(modeToAddInDb);

                    break;

                default:
                    return(false);
                }

                // Update power saving state only if the current state of power saving was off
                if (!App.CurrentUserEnvironment.LsSeekios.First(x => x.Idseekios == SeekiosUpdated.Idseekios).IsInPowerSaving)
                {
                    SeekiosUpdated.IsInPowerSaving = trackingSetting.IsPowerSavingEnabled;
                    App.CurrentUserEnvironment.LsSeekios.First(x => x.Idseekios == SeekiosUpdated.Idseekios).IsInPowerSaving = trackingSetting.IsPowerSavingEnabled;
                }

                // Save the setting tracking offline
                _saveDataService.SaveData(App.TrackingSetting, JsonConvert.SerializeObject(LsTrackingSetting));

                // Update the seekios
                if (idMode <= 0)
                {
                    return(false);
                }
                SeekiosUpdated.HasGetLastInstruction = false;
                if (MapViewModelBase.Seekios != null)
                {
                    MapViewModelBase.Seekios.HasGetLastInstruction = false;
                }

                // We locally delete the last mode and the alerts associate
                foreach (var mode in App.CurrentUserEnvironment.LsMode.Where(x => x.Seekios_idseekios == SeekiosUpdated.Idseekios))
                {
                    var idAlerts = App.CurrentUserEnvironment.LsAlert.Where(x => x.IdMode == mode.Idmode).Select(x => x.IdAlert).ToList();
                    foreach (var idAlert in idAlerts)
                    {
                        App.CurrentUserEnvironment.LsAlertRecipient.RemoveAll(x => x.IdAlert == idAlert);
                        App.CurrentUserEnvironment.LsAlert.RemoveAll(x => x.IdAlert == idAlert);
                    }
                }
                App.CurrentUserEnvironment.LsMode.RemoveAll(x => x.Seekios_idseekios == SeekiosUpdated.Idseekios);

                // Add the mode in local data
                var modeToAddInLocal = new ModeDTO()
                {
                    Idmode = idMode,
                    CountOfTriggeredAlert = 0,
                    DateModeCreation      = DateTime.UtcNow,
                    Device_iddevice       = modeToAddInDb.Device_iddevice,
                    Seekios_idseekios     = modeToAddInDb.Seekios_idseekios,
                    StatusDefinition_idstatusDefinition = (int)StatutDefinitionEnum.RAS,
                    Trame = modeToAddInDb.Trame,
                    ModeDefinition_idmodeDefinition = (int)modeDefinition,
                    IsPowerSavingEnabled            = modeToAddInDb.IsPowerSavingEnabled
                };
                App.CurrentUserEnvironment.LsMode.Add(modeToAddInLocal);

                // Handle alerts if it's required
                switch (modeDefinition)
                {
                case ModeDefinitionEnum.ModeDontMove:
                    // configure a bool to execute 2 back actions
                    App.Locator.ListAlert.Seekios = SeekiosUpdated;
                    var dontMoveAlerts = await _dataService.AlertsByMode(modeToAddInDb);

                    if (dontMoveAlerts != null)
                    {
                        foreach (AlertDTO a in dontMoveAlerts)
                        {
                            App.CurrentUserEnvironment.LsAlert.Add(a);
                        }
                    }
                    // Pourquoi on utilise le ModeZoneViewModel pour le DontMove???
                    App.Locator.ModeDontMove.LsAlertsModeDontMove?.Clear();
                    break;

                case ModeDefinitionEnum.ModeZone:
                    // il faut aussi aller chercher les alertes pour le nouveau mode avec leur nouveaux ids...
                    // vider la liste dans ModeZoneVM + ajouter les nlles alertes dans LsAlertes
                    var zoneAlerts = await _dataService.AlertsByMode(modeToAddInDb);

                    if (zoneAlerts != null)
                    {
                        foreach (AlertDTO a in zoneAlerts)
                        {
                            App.CurrentUserEnvironment.LsAlert.Add(a);
                        }
                    }
                    App.Locator.ModeZone.LsAlertsModeZone?.Clear();
                    break;
                }

                // Delete the seekios tracking object because it's a new mode
                var seekiosOnTrackingToDelete = App.Locator.Map.LsSeekiosOnTracking.FirstOrDefault(x => x.Seekios.Idseekios == SeekiosUpdated.Idseekios);
                if (seekiosOnTrackingToDelete != null)
                {
                    if (seekiosOnTrackingToDelete.Timer.IsRunning)
                    {
                        seekiosOnTrackingToDelete.Timer.Stop();
                    }
                    App.Locator.Map.LsSeekiosOnTracking.RemoveAll(x => x.Seekios.Idseekios == SeekiosUpdated.Idseekios);
                }

                // Setup a new seekios tracking object for a new timer
                if (modeToAddInLocal.ModeDefinition_idmodeDefinition == (int)ModeDefinitionEnum.ModeTracking)
                {
                    App.Locator.Map.AddSeekiosOnTracking(SeekiosUpdated, modeToAddInLocal);
                }

                // Hide loading layout
                _dialogService.HideLoadingLayout();
                return(true);
            }
            catch (TimeoutException)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.TimeoutError
                                              , Resources.TimeoutErrorTitle
                                              , Resources.Close, null));
            }
            catch (WebException)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.TimeoutError
                                              , Resources.TimeoutErrorTitle
                                              , Resources.Close, null));
            }
            catch (Exception)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.UnexpectedError
                                              , Resources.UnexpectedErrorTitle
                                              , Resources.Close, null));
            }
            _dialogService.HideLoadingLayout();
            return(false);
        }
        /// <summary>
        /// Refresh seekios position
        /// </summary>
        public async Task <bool> RefreshSeekiosPosition()
        {
            var seekiosToRefresh = App.Locator.DetailSeekios.SeekiosSelected;

            try
            {
                // If the seekios is already in refresh state
                if (LsSeekiosOnDemand.Any(x => x.Seekios.Idseekios == seekiosToRefresh.Idseekios))
                {
                    return(false);
                }

                // If user has enough credits
                int creditsDispo = 0;
                if (!int.TryParse(Helper.CreditHelper.TotalCredits, out creditsDispo))
                {
                    return(false);
                }
                if (creditsDispo <= 0)
                {
                    var msg   = Resources.UserNoRequestLeft;
                    var title = Resources.UserNoRequestLeftTitle;
                    await _dialogService.ShowMessage(msg, title);

                    return(false);
                }

                // If the seekios is in power saving, cancel the request
                if (App.CurrentUserEnvironment.LsSeekios.First(x => x.Idseekios == seekiosToRefresh.Idseekios).IsInPowerSaving == true)
                {
                    await _dialogService.ShowMessage(Resources.PowerSavingOn
                                                     , Resources.PowerSavingOnTitle
                                                     , Resources.PowerSavingTuto
                                                     , Resources.Close, (result2) => { if (result2)
                                                                                       {
                                                                                           App.Locator.Parameter.GoToTutorialPowerSaving();
                                                                                       }
                                                     });

                    return(false);
                }

                // Make the request in BDD
                _dialogService.ShowLoadingLayout();
                var result = await _dataService.RefreshSeekiosLocation(seekiosToRefresh.Idseekios);

                if (result != 1)
                {
                    var msg   = Resources.RefreshSeekiosFailed;
                    var title = Resources.RefreshSeekiosFailedTitle;
                    _dispatcherService.Invoke(async() => await _dialogService.ShowMessage(msg, title));
                }
                _dialogService.HideLoadingLayout();

                // Udpate the seekios
                var index = App.CurrentUserEnvironment.LsSeekios.IndexOf(App.CurrentUserEnvironment.LsSeekios.First(x => x.Idseekios == seekiosToRefresh.Idseekios));
                App.CurrentUserEnvironment.LsSeekios[index].DateLastOnDemandRequest = DateTime.Now;
                App.CurrentUserEnvironment.LsSeekios[index].HasGetLastInstruction   = false;
                App.Locator.DetailSeekios.SeekiosSelected = App.CurrentUserEnvironment.LsSeekios[index];

                // Add the new seekios is the refresh seekios list
                AddSeekiosOnDemand(seekiosToRefresh, DateTime.Now.AddSeconds(App.TIME_FOR_REFRESH_SEEKIOS_IN_SECOND));

                // Raise event for update UI
                OnSeekiosRefreshRequestSent?.Invoke(null, null);
                return(true);
            }

            catch (TimeoutException)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.TimeoutError
                                              , Resources.TimeoutErrorTitle
                                              , Resources.Close, null));
            }
            catch (WebException)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.TimeoutError
                                              , Resources.TimeoutErrorTitle
                                              , Resources.Close, null));
            }
            catch (Exception)
            {
                _dispatcherService.Invoke(async() => await _dialogService.ShowError(
                                              Resources.UnexpectedError
                                              , Resources.UnexpectedErrorTitle
                                              , Resources.Close, null));
            }
            _dialogService.HideLoadingLayout();
            return(false);
        }