public string UpdateUserREST(UserLegitimation user, Person person)
 {
     string statusMessage = null;
     try
     {
         UpdateUser(_dbName, _userName, _passWord, user, person, out statusMessage);
         if (statusMessage == null)
             statusMessage = "ok";
     }
     catch (Exception e)
     {
         //Handle exception
         statusMessage += "An exception has occured in UpdateUserREST method. " + e.Message;
     }
     //if (statusMessage != null)
     //    File.AppendAllText(@"C:\logs.txt", Environment.NewLine + "<statusMessage - " + DateTime.Now + ">: " + statusMessage);
     return statusMessage;
 }
        public void UpdateUser(string dbName, string dbUserName, string dbPassWord, UserLegitimation user, Person person, out string statusMessage)
        {
            statusMessage = null;
            try
            {
                MongoDatabase resultDB = GetMongoDatabase(dbName, dbUserName, dbPassWord);
                if (resultDB == null)
                {
                    statusMessage = "Database is null";
                    return;
                }
                user.userID = AuthenticateUser(_dbName, _userName, _passWord, user, out statusMessage);
                if (statusMessage != null)
                    return;
                MongoCollection<Person> persons = persons = resultDB.GetCollection<Person>("persons");
                if (persons.Count() > 0)
                {
                    var personQuery = Query<Person>.EQ(e => e.userID, user.userID);
                    if (personQuery != null)
                    {
                        persons.Remove(personQuery);
                    }
                }

                Person newPerson = new Person
                {
                    userID = user.userID,
                    GenderId = person.GenderId,
                    birthyearId = person.birthyearId,
                    occupationId = person.occupationId,
                    residenceId = person.residenceId,
                    areaId = person.areaId,
                    numChildrenId = person.numChildrenId,
                    maritalStatusId = person.maritalStatusId,
                    subscriptionId = person.subscriptionId
                };

                if (newPerson.birthyearId == 0)
                    newPerson.birthyearName = "NotProvided";
                else if (newPerson.birthyearId == 1)
                    newPerson.birthyearName = "Under18";
                else newPerson.birthyearName = newPerson.birthyearId.ToString();

                newPerson.GenderName = ((Gender)newPerson.GenderId).ToString();
                newPerson.occupationName = ((Occupation)newPerson.occupationId).ToString();
                newPerson.residenceName = ((Residence)newPerson.residenceId).ToString();
                newPerson.areaName = ((Area)newPerson.areaId).ToString();
                newPerson.numChildrenName = ((NumberOfChildren)newPerson.numChildrenId).ToString();
                newPerson.maritalStatusName = ((MaritalStatus)newPerson.maritalStatusId).ToString();
                newPerson.subscriptionName = ((Subscription)newPerson.subscriptionId).ToString();
                persons.Insert(newPerson);
            }
            catch (Exception e)
            {
                statusMessage += "An exception has occured in UpdateUser method. " + e.Message;
            }
        }
        public void InsertTripData(string dbName, string dbUserName, string dbPassWord, UserLegitimation user, Person person, Trip trip, List<TripChainJson> locations, List<TransportModeJson> modes, bool isInsert, out string statusMessage)
        {
            statusMessage = null;
            string locID = null;
            try
            {
                MongoDatabase resultDB = GetMongoDatabase(dbName, dbUserName, dbPassWord);
                if (resultDB == null)
                {
                    statusMessage = "Database is null";
                    return;
                }

                UpdateUser(_dbName, _userName, _passWord, user, person, out statusMessage);
                if (statusMessage != null) return;
                //Check locations exists. If not, add and return new locID. If exists, return locID.

                MongoCollection<TripChain> tripChains = resultDB.GetCollection<TripChain>("tripChains");
                MongoCollection<Location> mgLocations = resultDB.GetCollection<Location>("locations");
                MongoCollection<Mode> mgModes = resultDB.GetCollection<Mode>("modes");
                foreach (TripChainJson tj in locations)
                {
                    locID = CheckLocExists(tj.latitude, tj.longitude, mgLocations, out statusMessage);
                    if (locID == null && statusMessage == null)
                        locID = AddLocation(dbName, dbUserName, dbPassWord, tj, out statusMessage);
                    if (statusMessage != null) return;
                    TripChain tc = new TripChain
                    {
                        tripID = trip.tripID,
                        tripChainID = tj.timestamp.ToString(),
                        locationChainID = locID,
                        timeStamp = tj.timestamp,
                        accuracy = tj.accuracy,
                        altitude = tj.altitude,
                        altitudeAccuracy = tj.altitudeAccuracy,
                        heading = tj.heading,
                        speed = tj.speed
                    };
                    if (isInsert == false) //this trip chain is existed -> remove it -> insert new info with same id (= existed id)
                    {
                        var tripChainQuery = Query<TripChain>.EQ(e => e.tripChainID, tc.tripChainID);
                        if (tripChainQuery != null)
                            tripChains.Remove(tripChainQuery);
                    }
                    tripChains.Insert(tc);
                }

                foreach (TransportModeJson tm in modes)
                {
                    Mode m = new Mode
                    {
                        modeID = tm.time.ToString(),
                        tripID = trip.tripID,
                        timestamp = tm.time,
                        mode = tm.mode
                    };
                    if (isInsert == false) //this trip chain is existed -> remove it -> insert new info with same id (= existed id)
                    {
                        var modeQuery = Query<Mode>.EQ(e => e.timestamp, m.timestamp);
                        if (modeQuery != null)
                            mgModes.Remove(modeQuery);
                    }
                    mgModes.Insert(m);
                }

                MongoCollection<Trip> trips = resultDB.GetCollection<Trip>("trips");
                //tripID will be made from the front end
                Trip newTrip = new Trip
                {
                    tripID = trip.tripID,
                    userID = user.userID,
                    distance = trip.distance,
                    tripDate = trip.tripDate,
                    tripPurposeId = trip.tripPurposeId,
                    tripPurposeName = ((TripPurpose)trip.tripPurposeId).ToString()
                };
                if (isInsert == false) //this trip chain is existed -> remove it -> insert new info with same id (= existed id)
                {
                    var tripQuery = Query<Trip>.EQ(e => e.tripID, newTrip.tripID);
                    if (tripQuery != null)
                        trips.Remove(tripQuery);
                }
                trips.Insert(newTrip);
            }
            catch (Exception e)
            {
                statusMessage += "An exception has occured in InsertTripData method. " + e.Message;
            }
        }
        /// <summary>        
        /// </summary>
        /// <param name="user"></param>
        /// <param name="trip"></param>
        /// <param name="tripChain"></param>
        /// <returns></returns>
        public string UpdateTripDataREST(long id, UserLegitimation user, Person person, TripJson trip)
        {
            string statusMessage = null;
            Trip tripData = new Trip();
            List<TripChainJson> locations = new List<TripChainJson>();
            List<TransportModeJson> modes = new List<TransportModeJson>();

            try
            {
                statusMessage = ExtractTripData(id, user, person, trip, out tripData, out locations, out modes, out statusMessage);
                if (statusMessage == null)
                {
                    InsertTripData(_dbName, _userName, _passWord, user, person, tripData, locations, modes, false, out statusMessage);
                    if (statusMessage == null)
                        statusMessage = "ok";
                }
            }
            catch (Exception e)
            {
                statusMessage += "An exception has occured in UpdateTripDataREST method. " + e.Message;
            }
            //if (statusMessage != null)
            //    File.AppendAllText(@"C:\logs.txt", Environment.NewLine + "<statusMessage - " + DateTime.Now + ">: " + statusMessage);
            return statusMessage;
        }
        public string ExtractTripData(long id, UserLegitimation user, Person person, TripJson trip, out Trip tripData, out List<TripChainJson> locations, out List<TransportModeJson> modes, out string statusMessage)
        {
            statusMessage = null;
            tripData = new Trip();
            locations = new List<TripChainJson>();
            modes = new List<TransportModeJson>();
            try
            {
                tripData.tripID = id.ToString();
                if (trip.meta != null)
                {
                    tripData.tripDate = new DateTime(1970, 1, 1) + new TimeSpan(trip.meta.startTime * 10000);
                    tripData.distance = trip.meta.distance;
                    tripData.tripPurposeId = trip.meta.purpose;
                }
                if (trip.entries != null)
                {
                    foreach (var e in trip.entries)
                    {
                        TripChainJson tcjs = new TripChainJson()
                        {
                            timestamp = e.timestamp,
                            latitude = e.latitude,
                            longitude = e.longitude,
                            altitude = e.altitude,
                            accuracy = e.accuracy,
                            altitudeAccuracy = e.altitudeAccuracy,
                            heading = e.heading,
                            speed = e.speed
                        };
                        locations.Add(tcjs);
                    }
                }

                if (trip.modes != null)
                {
                    foreach (var m in trip.modes)
                    {
                        TransportModeJson tmjs = new TransportModeJson()
                        {
                            time = m.time,
                            mode = m.mode
                        };
                        modes.Add(tmjs);
                    }
                }
            }
            catch (Exception e)
            {
                statusMessage = "An exception has occured in ExtractTripData method. " + e.Message;
            }
            return statusMessage;
        }