Ejemplo n.º 1
0
        public async Task <bool> SaveItemInDBTask(MedicationSchedule element)
        {
            try
            {
                _db = await SqlHelper <MedicineServerRecords> .CreateAsync();

                Log.Error("Storage class saving element..", element.ToString());
                if (!(await SearchItemTask(element.Uuid)))
                {
                    Log.Error("Storage class", "inserting in db..");
                    await _db.Insert(new MedicineServerRecords
                    {
                        Title          = element.Title,
                        Content        = element.Content,
                        DateTime       = element.Timestampstring,
                        Uuid           = element.Uuid,
                        Postpone       = element.Postpone + "",
                        IdNotification = "" + element.IdNotification
                    });

                    Log.Error("Storage class", "element saved");
                    return(true);
                }
            }
            catch (Exception e)
            {
                Log.Error("STORAGE error", e.Message);
            }

            return(false);
        }
        /// <summary>
        /// Create a medication schedule
        /// POST: api/MedicationSchedule/GetMedicationSchedule/
        /// </summary>
        /// <param name="medicationSchedule">A MedicationSchedule object.</param>
        /// <returns>Id of the medication schedule created.</returns>
        private MedicationSchedule CreateSingleMedicationSechudle(MedicationSchedule medicationSchedule)
        {
            //TODO: If the timeframe is week, then repeat on should not be empty
            try
            {
                var command = new SqlCommand("INSERT INTO MedicationSchedule (MEDICATIONID, NAME, MEDINFO, EVERY, COUNT, DATE, HOUR, MINUTE, TAKEN) " +
                                             "VALUES(@MEDICATIONID, @NAME, @MEDINFO, @EVERY, @COUNT, @DATE, @HOUR, @MINUTE, @TAKEN); SELECT SCOPE_IDENTITY();", Connections.pillboxDatabase);

                command.Parameters.AddWithValue("@MEDICATIONID", medicationSchedule.MedicationId);
                command.Parameters.AddWithValue("@NAME", medicationSchedule.Name);
                command.Parameters.AddWithValue("@MEDINFO", medicationSchedule.MedInfo);
                command.Parameters.AddWithValue("@EVERY", medicationSchedule.Every);
                command.Parameters.AddWithValue("@COUNT", medicationSchedule.Count);
                command.Parameters.AddWithValue("@DATE", medicationSchedule.Date);
                command.Parameters.AddWithValue("@HOUR", medicationSchedule.Hour);
                command.Parameters.AddWithValue("@MINUTE", medicationSchedule.Minute);
                command.Parameters.AddWithValue("@TAKEN", medicationSchedule.Taken);

                Connections.pillboxDatabase.Open();

                var medScheduleId = Convert.ToInt32(command.ExecuteScalar());
                medicationSchedule.Id = medScheduleId;
                return(medicationSchedule); //ok
                //return Ok(medScheduleId);
            }
            catch (Exception ex)
            {
                return(null); //bad request
                //return BadRequest($"CreateMedicationSchedule() error \n {ex.ToString()}");
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
        public ActionResult <int> CreateMedicationSchedule([FromBody] MedicationSchedule medicationSchedule)
        {
            try
            {
                var command = new SqlCommand("INSERT INTO MedicationSchedule (MEDICATIONID, NAME, MEDINFO, EVERY, COUNT, DATE, HOUR, MINUTE, TAKEN) " +
                                             "VALUES(@MEDICATIONID, @NAME, @MEDINFO, @EVERY, @COUNT, @DATE, @HOUR, @MINUTE, @TAKEN); SELECT SCOPE_IDENTITY();", Connections.pillboxDatabase);

                command.Parameters.AddWithValue("@MEDICATIONID", medicationSchedule.MedicationId);
                command.Parameters.AddWithValue("@NAME", medicationSchedule.Name);
                command.Parameters.AddWithValue("@MEDINFO", medicationSchedule.MedInfo);
                command.Parameters.AddWithValue("@EVERY", medicationSchedule.Every);
                command.Parameters.AddWithValue("@COUNT", medicationSchedule.Count);
                command.Parameters.AddWithValue("@DATE", medicationSchedule.Date);
                command.Parameters.AddWithValue("@HOUR", medicationSchedule.Hour);
                command.Parameters.AddWithValue("@MINUTE", medicationSchedule.Minute);
                command.Parameters.AddWithValue("@TAKEN", medicationSchedule.Taken);

                Connections.pillboxDatabase.Open();

                var medScheduleId = Convert.ToInt32(command.ExecuteScalar());

                return(Ok(medScheduleId));
            }
            catch (Exception ex)
            {
                return(BadRequest($"CreateMedicationSchedule() error \n {ex.ToString()}"));
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
        public ActionResult <string> EditMedicationSchedule([FromBody] MedicationSchedule medicationSchedule)
        {
            try
            {
                var command = new SqlCommand("UPDATE MedicationSchedule SET MEDICATIONID=@MEDICATIONID, NAME=@NAME, MEDINFO=@MEDINFO, EVERY=@EVERY " +
                                             ", COUNT=@COUNT, DATE=@DATE, HOUR=@HOUR, MINUTE=@MINUTE, TAKEN=@TAKEN " +
                                             "  WHERE ID=@ID", Connections.pillboxDatabase);

                command.Parameters.AddWithValue("@ID", medicationSchedule.Id);
                command.Parameters.AddWithValue("@MEDICATIONID", medicationSchedule.MedicationId);
                command.Parameters.AddWithValue("@NAME", medicationSchedule.Name);
                command.Parameters.AddWithValue("@MEDINFO", medicationSchedule.MedInfo);
                command.Parameters.AddWithValue("@EVERY", medicationSchedule.Every);
                command.Parameters.AddWithValue("@COUNT", medicationSchedule.Count);
                command.Parameters.AddWithValue("@DATE", medicationSchedule.Date);
                command.Parameters.AddWithValue("@HOUR", medicationSchedule.Hour);
                command.Parameters.AddWithValue("@MINUTE", medicationSchedule.Minute);
                command.Parameters.AddWithValue("@TAKEN", medicationSchedule.Taken);

                Connections.pillboxDatabase.Open();

                command.ExecuteScalar();

                return(Ok($"Successfully updated Medication: {medicationSchedule.Id}"));
            }
            catch (Exception ex)
            {
                return(BadRequest($"CreateMedicationSchedule() error \n {ex.ToString()}"));
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
Ejemplo n.º 5
0
        // will be removed & moved to NetworkingData class
        public async void saveElementMedSer(MedicationSchedule med)
        {
            try
            {
                var c = await _db.QueryValuations($"SELECT * from MedicineServerRecords WHERE Uuid ='{med.Uuid}'");

                Log.Error("Count current save Element", c.Count() + "");
                if (c.Count() == 0)
                {
                    Log.Error("STORAGE", "se introduc date in DB..");
                    await _db.Insert(new MedicineServerRecords
                    {
                        Title          = med.Title,
                        Content        = med.Content,
                        DateTime       = med.Timestampstring,
                        Uuid           = med.Uuid,
                        Postpone       = med.Postpone + "",
                        IdNotification = med.IdNotification + ""
                    });

                    _medicationSchedules.Add(med);
                    Log.Error("STORAGE", _medicationSchedules.Count() + "");
                }
            }
            catch (Exception e)
            {
                Log.Error("ERR", e.ToString());
            }
        }
Ejemplo n.º 6
0
        public async Task <bool> SaveListInDBTask(List <MedicationSchedule> list)
        {
            _db = await SqlHelper <MedicineServerRecords> .CreateAsync();

            foreach (MedicationSchedule element in list)
            {
                Log.Error("NetworkingData class saving..", element.ToString());
                if (!(await SearchItemTask(element.Uuid)))
                {
                    MedicationSchedule objMed = await getElementByUUID(element.Uuid);

                    Log.Error("NetworkingData class", "saving obj pi id " + element.IdNotification);
                    if (objMed != null && element.IdNotification == 0)
                    {
                        element.IdNotification = objMed.IdNotification;
                        Log.Error("NetworkingData class", "saving obj pi id " + objMed.IdNotification);
                    }
                    Log.Error("NetworkingData class", "inserting in db..");
                    await _db.Insert(new MedicineServerRecords
                    {
                        Title          = element.Title,
                        Content        = element.Content,
                        DateTime       = element.Timestampstring,
                        Uuid           = element.Uuid,
                        Postpone       = element.Postpone + "",
                        IdNotification = "" + element.IdNotification
                    });
                }
            }

            Log.Error("NeworkingData class", "saved");

            return(true);
        }
Ejemplo n.º 7
0
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            var holder = viewHolder as MedicineLostAdapterViewHolder;
            MedicationSchedule medication = list[position];

            if (medication.Uuid.Contains("disease"))
            {
                holder.ivIcon.SetImageResource(Resource.Drawable.pill_lost_pers);
                holder.tvDateTime.SetTextColor(Color.ParseColor("#1AB188"));
            }
            else
            {
                holder.ivIcon.SetImageResource(Resource.Drawable.pill_lost);
                holder.tvDateTime.SetTextColor(Color.ParseColor("#f02b4c"));
            }

            holder.tvMedSer.Text  = medication.Title;
            holder.tvContent.Text = medication.Content;
            holder.medication     = medication;
            holder.listener       = listener;


            string hourPrefix   = Convert.ToDateTime(medication.Timestampstring).Hour < 10 ? "0" : "";
            string minutePrefix = Convert.ToDateTime(medication.Timestampstring).Minute < 10 ? "0" : "";

            holder.tvDateTime.Text =
                $"{Convert.ToDateTime(medication.Timestampstring).Day}/{Convert.ToDateTime(medication.Timestampstring).Month}/{Convert.ToDateTime(medication.Timestampstring).Year} {hourPrefix}{Convert.ToDateTime(medication.Timestampstring).Hour.ToString()}:{minutePrefix}{Convert.ToDateTime(medication.Timestampstring).Minute.ToString()}";//medication.Timestampstring.Substring(0, medication.Timestampstring.Length - 6);

            Log.Error("ADAPTER MEDICINE LOST", "on bind view holder");
        }
 public void AddItem(MedicationSchedule med)
 {
     if (med != null)
     {
         list.Add(med);
         NotifyDataSetChanged();
     }
 }
 public void removeItem(MedicationSchedule med)
 {
     if (med != null)
     {
         list.Remove(med);
         NotifyDataSetChanged();
     }
 }
Ejemplo n.º 10
0
 private bool ItemInListFound(MedicationSchedule item, List <MedicationSchedule> list)
 {
     foreach (MedicationSchedule variable in list)
     {
         if (variable.Uuid.Equals(item.Uuid))
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 11
0
 public async Task insertElementMedSer(MedicationSchedule element)
 {
     Log.Error("STORAGE", "se introduc date in DB..");
     await _db.Insert(new MedicineServerRecords
     {
         Title          = element.Title,
         Content        = element.Content,
         DateTime       = element.Timestampstring,
         Uuid           = element.Uuid,
         Postpone       = element.Postpone + "",
         IdNotification = element.IdNotification + ""
     });
 }
        public ActionResult <List <MedicationSchedule> > GetAllMedicatoinScheduleByDay(long personId, DateTime?day = null)
        {
            if (day == null)
            {
                day = DateTime.Now;
            }

            try
            {
                var command = new SqlCommand("SELECT * " +
                                             "FROM MedicationSchedule WHERE 1 = 1 " +
                                             "AND CAST([Date] AS Date) = CAST(@day AS Date) " +
                                             "AND medicationId IN " +
                                             "   (SELECT DISTINCT med.id FROM Medication AS med WHERE personId=@personId)", Connections.pillboxDatabase);
                command.Parameters.AddWithValue("@day", day);
                command.Parameters.AddWithValue("@personId", personId);

                Connections.pillboxDatabase.Open();

                SqlDataReader reader = command.ExecuteReader();

                var medSchedules = new List <MedicationSchedule>();

                while (reader.Read())
                {
                    var medicationSchedule = new MedicationSchedule(
                        (long)reader["ID"],
                        (long)reader["MEDICATIONID"],
                        (string)reader["NAME"],
                        (string)reader["MEDINFO"],
                        (string)reader["EVERY"],
                        (int)reader["COUNT"],
                        (DateTime)reader["DATE"],
                        (int)reader["HOUR"],
                        (int)reader["MINUTE"],
                        (bool)reader["TAKEN"]
                        );
                    medSchedules.Add(medicationSchedule);
                }
                return(medSchedules);
            }
            catch (Exception ex)
            {
                return(BadRequest($"GetAllMedicatoinScheduleByDay({personId},{day}) method. \n::::\n" + ex.ToString()));
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
Ejemplo n.º 13
0
        public void OnMedSerClick(MedicationSchedule med)
        {
            var      alert       = new AlertDialog.Builder(Activity);
            var      medDate     = Convert.ToDateTime(med.Timestampstring);
            DateTime currentDate = DateTime.Now;

            if (medDate > currentDate)
            {
                alert.SetMessage("Pentru afectiunea " + med.Title + ", medicamentul " + med.Content + " nu se poate marca administrat.");
                alert.SetPositiveButton("Ok", (senderAlert, args) => { });
            }
            Dialog dialog = alert.Create();

            dialog.Show();
        }
Ejemplo n.º 14
0
 public bool SendMedicationTask(JSONArray mArray, MedicationSchedule med, DateTime now)
 {
     AddMedicine(med.Uuid, now);
     Log.Error("MEDICINE LOST", "Medication service started");
     _medicationLostIntent = new Intent(Context, typeof(MedicationService));
     if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
     {
         Context.StartForegroundService(_medicationLostIntent);
     }
     else
     {
         Context.StartService(_medicationLostIntent);
     }
     Storage.GetInstance().removeMedSer(med.Uuid);
     return(true);
 }
Ejemplo n.º 15
0
        private static List <MedicationSchedule> ConvertPersonalMedicationListToMedicationSchedules(List <Disease> LD)
        {
            var listMedSchPersonal = new List <MedicationSchedule>();

            foreach (Disease item in LD)
            {
                foreach (Medicine itemMed in item.ListOfMedicines)
                {
                    foreach (Hour itemHour in itemMed.Hours)
                    {
                        if (itemHour.HourName.Equals("24:00"))
                        {
                            itemHour.HourName = "23:59";
                        }
                        TimeSpan tspan = TimeSpan.Parse(itemHour.HourName);
                        Log.Error("TIME SPAN: ", tspan.ToString());
                        var dtMed = new DateTime(itemMed.Date.Year, itemMed.Date.Month, itemMed.Date.Day, tspan.Hours, tspan.Minutes, tspan.Seconds);
                        Log.Error("MEDICINE LOST", "item med: " + dtMed);

                        DateTime currentDate = DateTime.Now;
                        if (dtMed < currentDate)
                        {
                            TimeSpan difference = DateTime.Now.Subtract(dtMed);
                            int      days       = (int)difference.TotalDays + 1;
                            Log.Error("MEDICINE LOST DAYS", "days betweet 2 dates: " + days);
                            if (itemMed.NumberOfDays != 0)
                            {
                                days = days >= itemMed.NumberOfDays
                                    ? itemMed.NumberOfDays
                                    : itemMed.NumberOfDays - days;
                            }

                            Log.Error("MEDICINE LOST DAYS", "days: " + days);
                            var objMedSch = new MedicationSchedule("disease" + item.Id + "med" + itemMed.IdMed + "hour" + itemHour.Id + "time" + dtMed, dtMed.ToString(), item.DiseaseName, itemMed.Name, 5, 0);
                            listMedSchPersonal.Add(objMedSch);
                            for (var j = 1; j < days; j++)
                            {
                                dtMed     = dtMed.AddDays(1);
                                objMedSch = new MedicationSchedule("disease" + item.Id + "med" + itemMed.IdMed + "hour" + itemHour.Id + "time" + dtMed, dtMed.ToString(), item.DiseaseName, itemMed.Name, 5, 0);
                                listMedSchPersonal.Add(objMedSch);
                            }
                        }
                    }
                }
            }
            return(listMedSchPersonal.OrderBy(x => DateTime.Parse(x.Timestampstring)).ToList());
        }
Ejemplo n.º 16
0
        private bool IsItemRemoved(List <MedicationSchedule> listWithRemovedItems, MedicationSchedule fileItem)
        {
            var isItemRemoved = false;

            if (listWithRemovedItems.Count != 0)
            {
                var itemToFind = new MedicationSchedule(fileItem.Uuid, fileItem.Timestampstring, fileItem.Title,
                                                        fileItem.Content, fileItem.Postpone, fileItem.IdNotification);
                itemToFind.Uuid += "removed";
                if (ItemInListFound(itemToFind, listWithRemovedItems))
                {
                    isItemRemoved = true;
                }
            }

            return(isItemRemoved);
        }
Ejemplo n.º 17
0
        private bool isItemInListOrListIsEmpty(MedicationSchedule item, List <MedicationSchedule> list)
        {
            if (list.Count == 0)
            {
                return(false);
            }

            foreach (MedicationSchedule ms in list)
            {
                if (ms.Uuid == item.Uuid)
                {
                    return(true);
                }
            }

            return(false);
        }
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            var holder = viewHolder as MedicineServerAdapterViewHolder;
            MedicationSchedule medication = list[position];

            holder.tvMedSer.Text  = medication.Title;
            holder.tvContent.Text = medication.Content;
            holder.medication     = medication;
            holder.listener       = listener;


            string hourPrefix   = Convert.ToDateTime(medication.Timestampstring).Hour < 10 ? "0" : "";
            string minutePrefix = Convert.ToDateTime(medication.Timestampstring).Minute < 10 ? "0" : "";

            holder.tvDateTime.Text =
                $"{Convert.ToDateTime(medication.Timestampstring).Day}/{Convert.ToDateTime(medication.Timestampstring).Month}/{Convert.ToDateTime(medication.Timestampstring).Year} {hourPrefix}{Convert.ToDateTime(medication.Timestampstring).Hour.ToString()}:{minutePrefix}{Convert.ToDateTime(medication.Timestampstring).Minute.ToString()}";//medication.Timestampstring.Substring(0, medication.Timestampstring.Length - 6);

            Log.Error("MEDICINE SERVER", "on bind view holder");
        }
        public ActionResult <List <MedicationSchedule> > GetMedicationScheduleByMedication(int medicationId)
        {
            try
            {
                var command = new SqlCommand("SELECT * FROM MedicationSchedule WHERE MEDICATIONID=@MEDICATIONID", Connections.pillboxDatabase);
                command.Parameters.AddWithValue("@MEDICATIONID", medicationId);

                Connections.pillboxDatabase.Open();

                SqlDataReader reader = command.ExecuteReader();

                var medSchedules = new List <MedicationSchedule>();

                while (reader.Read())
                {
                    var medicationSchedule = new MedicationSchedule(
                        (long)reader["ID"],
                        (long)reader["MEDICATIONID"],
                        (string)reader["NAME"],
                        (string)reader["MEDINFO"],
                        (string)reader["EVERY"],
                        (int)reader["COUNT"],
                        (DateTime)reader["DATE"],
                        (int)reader["HOUR"],
                        (int)reader["MINUTE"],
                        (bool)reader["TAKEN"]
                        );
                    medSchedules.Add(medicationSchedule);
                }
                return(medSchedules);
            }
            catch (Exception ex)
            {
                return(BadRequest($"GetMedicationSchedule({medicationId}) method. \n::::\n" + ex.ToString()));
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
        public ActionResult <MedicationSchedule> GetMedicationSchedule(long id)
        {
            try
            {
                var command = new SqlCommand("SELECT * FROM MedicationSchedule WHERE ID=@ID", Connections.pillboxDatabase);
                command.Parameters.AddWithValue("@ID", id);

                Connections.pillboxDatabase.Open();

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    var medicationSchedule = new MedicationSchedule(
                        (long)reader["ID"],
                        (long)reader["MEDICATIONID"],
                        (string)reader["NAME"],
                        (string)reader["MEDINFO"],
                        (string)reader["EVERY"],
                        (int)reader["COUNT"],
                        (DateTime)reader["DATE"],
                        (int)reader["HOUR"],
                        (int)reader["MINUTE"],
                        (bool)reader["TAKEN"]
                        );
                    return(medicationSchedule);
                }

                throw new Exception($"Error. No data to read for MedicationSchedule Id: {id}");
            }
            catch (Exception ex)
            {
                return(BadRequest($"GetMedicationSchedule({id}) method. \n::::\n" + ex.ToString()));
            }
            finally
            {
                Connections.pillboxDatabase.Close();
            }
        }
Ejemplo n.º 21
0
        // will be updated to save Storage type of data - personal medication
        public async Task <bool> saveMedSer(List <MedicationSchedule> list)
        {
            Log.Error("STORAGE", "saveMedSer " + list.Count);
            _db = await SqlHelper <MedicineServerRecords> .CreateAsync();

            if (list.Count != 0)
            {
                _medicationSchedules = list;
                foreach (MedicationSchedule element in _medicationSchedules)
                {
                    MedicationSchedule objMed = await getElementByUUID(element.Uuid);

                    if (objMed != null && element.IdNotification == 0)
                    {
                        element.IdNotification = objMed.IdNotification;
                    }
                    var c = await _db.QueryValuations($"SELECT * from MedicineServerRecords WHERE Uuid ='{element.Uuid}'");

                    Log.Error("Count current saveMedSer", c.Count() + "");
                    if (c.Count() == 0)
                    {
                        await insertElementMedSer(element);
                    }
                    else
                    {
                        //TODO update pi's id if it's different than 0
                        Log.Error("STORAGE", "element.idNotification: " + element.IdNotification + ", objMed.idNotification " + objMed.IdNotification);
                        if (element.IdNotification != 0 && objMed.IdNotification != 0)
                        {
                            // await removeMedSer(element.Uuid);
                            // await insertElementMedSer(element);
                            Log.Error("STORAGE", "remove & insert element for pi's id != 0 and uuid already exists");
                        }
                    }
                }
            }
            Log.Error("STORAGE", "finalizare");
            return(true);
        }
        private DateTime parseTimestampStringToDate(MedicationSchedule ms)
        {
            DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            {
                TimeZone = TimeZone.GetTimeZone("UTC")
            };
            var date = new DateTime();

            try
            {
                date = DateTime.Parse(ms.Timestampstring);
                DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
                {
                    TimeZone = TimeZone.GetTimeZone("PST")
                };
                Log.Error(Log_Tag, "timestampstring parsed" + date.ToLocalTime().ToString());
            }
            catch (ParseException e)
            {
                e.PrintStackTrace();
            }
            return(date.ToLocalTime());
        }
Ejemplo n.º 23
0
        public async Task <bool> RemoveItemFromDBTask(MedicationSchedule item)
        {
            try
            {
                Log.Error("STORAGE class", " item arrived: " + item.ToString());

                if (item.Uuid.Contains("removed"))
                {
                    return(false);
                }
                _db = await SqlHelper <MedicineServerRecords> .CreateAsync();

                string newUuid = item.Uuid + "removed";
                await _db.QueryValuations($"update MedicineServerRecords set Uuid='{newUuid}' where Uuid ='{item.Uuid}'");

                Log.Error("STORAGE class deleted item new UUid: ", (await getElementByUUID(newUuid)).ToString());
            }
            catch (Exception e)
            {
                Log.Error("STORAGE class ERROR", e.Message);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 24
0
        public void OnMedLostClick(MedicationSchedule med)
        {
            Log.Error("MEDICINE LOST", "med clicked: " + med.ToString());
            var      alert       = new AlertDialog.Builder(Activity);
            var      medDate     = Convert.ToDateTime(med.Timestampstring);
            DateTime currentDate = DateTime.Now;

            if (medDate < currentDate)
            {
                alert.SetMessage("Pentru afectiunea " + med.Title + ", medicamentul " + med.Content + " se va marca administrat.");
                alert.SetPositiveButton("Da", async(senderAlert, args) =>
                {
                    Log.Error("MEDICINE LOST", "DA clicked");
                    switch (int.Parse(Utils.GetDefaults("UserType")))
                    {
                    case 3:
                        //LoadType3();
                        var isSent = false;
                        if (med.Uuid.Contains("disease"))
                        {
                            bool isDeleted = await Storage.GetInstance().RemoveItemFromDBTask(med);
                            if (isDeleted)
                            {
                                Log.Error("MEDICINE LOST STORAGE", "deleted succesfully");
                                isSent = true;
                            }
                            else
                            {
                                Log.Error("MEDICINE LOST STORAGE", "something went wrong on delete item");
                            }
                        }
                        else
                        {
                            DateTime now     = DateTime.Now;
                            JSONArray mArray = new JSONArray().Put(new JSONObject().Put("uuid", med.Uuid)
                                                                   .Put("date", now.ToString("yyyy-MM-dd HH:mm:ss")));
                            isSent = SendMedicationTask(mArray, med, now);
                        }

                        if (isSent)
                        {
                            Toast.MakeText(Context, "Medicament administrat.", ToastLength.Long).Show();
                            _medicineLostAdapter.removeItem(med);
                            _medicineLostAdapter.NotifyDataSetChanged();
                        }
                        cwEmpty.Visibility = _medicationsLost.Count == 0 ? ViewStates.Visible : ViewStates.Gone;
                        break;

                    case 4:
                        // LoadType4();
                        var isMarked         = false;
                        bool isAdministrated = await Storage.GetInstance().RemoveItemFromDBTask(med);
                        if (isAdministrated)
                        {
                            Log.Error("MEDICINE LOST STORAGE", "deleted succesfully");
                            isMarked = true;
                        }
                        else
                        {
                            Log.Error("MEDICINE LOST STORAGE", "something went wrong on delete item");
                        }

                        if (isMarked)
                        {
                            Toast.MakeText(Context, "Medicament administrat.", ToastLength.Long).Show();
                            _medicineLostAdapter.removeItem(med);
                            _medicineLostAdapter.NotifyDataSetChanged();
                        }
                        cwEmpty.Visibility = _medicationsLost.Count == 0 ? ViewStates.Visible : ViewStates.Gone;

                        break;

                    default:
                        Log.Error("MEDICINE LOST", "wrong type");
                        break;
                    }
                });
                alert.SetNegativeButton("Nu", (senderAlert, args) => { });
            }
            else
            {
                alert.SetMessage("Pentru afectiunea " + med.Title + ", medicamentul " + med.Content + " nu se poate marca administrat.");
                alert.SetPositiveButton("Ok", (senderAlert, args) => { });
            }
            Dialog dialog = alert.Create();

            dialog.Show();
        }
Ejemplo n.º 25
0
        private async Task <List <MedicationSchedule> > GetMergedList(List <MedicationSchedule> listFromFileConverted, List <MedicationSchedule> listFromLocalDb)
        {
            var listWithRemovedItems = new List <MedicationSchedule>(listFromLocalDb.Where(c => c.Uuid.Contains("removed")).ToList());
            var finalList            = new List <MedicationSchedule>();

            foreach (MedicationSchedule fileItem in listFromFileConverted)
            {
                string diseasemedFile = fileItem.Uuid.Split("hour")[0];
                string hourFile       = fileItem.Uuid.Split("hour")[1];

                for (var i = 0; i < listFromLocalDb.Count; i++)
                {
                    MedicationSchedule dbItem       = listFromLocalDb[i];
                    string             diseasemedDB = dbItem.Uuid.Split("hour")[0];
                    string             hourDB       = dbItem.Uuid.Split("hour")[1];

                    if (IsItemRemoved(listWithRemovedItems, fileItem))
                    {
                        continue;
                    }
                    if (diseasemedFile.Equals(diseasemedDB))
                    {
                        if (hourFile.Equals(hourDB))
                        {
                            finalList.Add(dbItem);
                        }
                        else
                        {
                            if (!ItemInListFound(dbItem, listFromFileConverted))
                            {
                                continue;
                            }
                            if (ItemInListFound(fileItem, listFromLocalDb))
                            {
                                continue;
                            }
                            if (fileItem.Uuid.Contains("removed"))
                            {
                                continue;
                            }
                            Log.Error("STORAGE class UPDATE", "element to save: " + fileItem.ToString());
                            DateTime currentDate = DateTime.Now;
                            var      medDate     = Convert.ToDateTime(fileItem.Timestampstring);
                            if (medDate > currentDate)
                            {
                                continue;
                            }
                            if (await SaveItemInDBTask(fileItem))
                            {
                                listFromLocalDb.Add(fileItem);
                                finalList.Add(fileItem);
                            }
                            finalList.Remove(fileItem);
                        }
                    }
                    else
                    {
                        if (ItemInListFound(fileItem, listFromLocalDb))
                        {
                            continue;
                        }
                        Log.Error("STORAGE class", "element to save: " + fileItem.ToString());
                        DateTime currentDate = DateTime.Now;
                        var      medDate     = Convert.ToDateTime(fileItem.Timestampstring);
                        if (medDate > currentDate)
                        {
                            continue;
                        }
                        bool isSaved = await SaveItemInDBTask(fileItem);

                        if (isSaved)
                        {
                            listFromLocalDb.Add(fileItem);
                            finalList.Add(fileItem);
                        }

                        finalList.Remove(fileItem);
                    }
                }
            }
            return(finalList);
        }
        public ActionResult <List <MedicationSchedule> > CreateNotificationSchedule([FromBody] List <MedicationSchedule> medicationSchedules, int repeatNotification)
        {
            //TODO: If the timeframe is week, then repeat on should not be empty
            List <MedicationSchedule> notificationSchedule = new List <MedicationSchedule>();

            try
            {
                if (medicationSchedules.Count <= 0)
                {
                    return(BadRequest("No medication schedules given"));
                }

                medicationSchedules = medicationSchedules.OrderBy(x => x.Date).ThenBy(x => x.Hour).ThenBy(x => x.Minute).ToList();
                var date = new DateTime();
                date = medicationSchedules.First().Date;
                var count = medicationSchedules.First().Count;
                var r     = repeatNotification / Convert.ToDouble(medicationSchedules.Count);
                var daysWithNotification = Convert.ToInt32(Math.Ceiling(repeatNotification / Convert.ToDouble(medicationSchedules.Count)));
                var refillReminderSet    = false;

                while (repeatNotification > 0)
                {
                    foreach (var medSchedule in medicationSchedules)
                    {
                        var temp = new MedicationSchedule
                        {
                            Id           = medSchedule.Id,
                            MedicationId = medSchedule.MedicationId,
                            Name         = medSchedule.Name,
                            MedInfo      = medSchedule.MedInfo,
                            Every        = medSchedule.Every,
                            Count        = medSchedule.Count,
                            Date         = date,
                            Hour         = medSchedule.Hour,
                            Minute       = medSchedule.Minute,
                            Taken        = medSchedule.Taken
                        };

                        if (daysWithNotification <= 7 && !refillReminderSet)
                        {
                            //var refillCommand = new SqlCommand("INSERT INTO MedicationSchedule (MEDICATIONID, NAME, MEDINFO, EVERY, COUNT, DATE, HOUR, MINUTE, TAKEN) " +
                            //                "VALUES(@MEDICATIONID, @NAME, @MEDINFO, @EVERY, @COUNT, @DATE, @HOUR, @MINUTE, @TAKEN); SELECT SCOPE_IDENTITY();", Connections.pillboxDatabase);

                            //refillCommand.Parameters.AddWithValue("@MEDICATIONID", medSchedule.MedicationId);
                            //refillCommand.Parameters.AddWithValue("@NAME", $"Pills for {medSchedule.Name} running low.");
                            //refillCommand.Parameters.AddWithValue("@MEDINFO", $"Only {daysWithNotification} remaining.");
                            //refillCommand.Parameters.AddWithValue("@EVERY", "day");
                            //refillCommand.Parameters.AddWithValue("@COUNT", 1);
                            //refillCommand.Parameters.AddWithValue("@DATE", temp.Date);
                            //refillCommand.Parameters.AddWithValue("@HOUR", medSchedule.Hour);
                            //refillCommand.Parameters.AddWithValue("@MINUTE", medSchedule.Minute);
                            //refillCommand.Parameters.AddWithValue("@TAKEN", medSchedule.Taken);

                            //Connections.pillboxDatabase.Open();
                            //var refillId = Convert.ToInt32(refillCommand.ExecuteScalar());
                            //temp.Id = refillId;
                            //notificationSchedule.Add(temp);
                            //Connections.pillboxDatabase.Close();

                            //refillReminderSet = true;
                        }

                        var command = new SqlCommand("INSERT INTO MedicationSchedule (MEDICATIONID, NAME, MEDINFO, EVERY, COUNT, DATE, HOUR, MINUTE, TAKEN) " +
                                                     "VALUES(@MEDICATIONID, @NAME, @MEDINFO, @EVERY, @COUNT, @DATE, @HOUR, @MINUTE, @TAKEN); SELECT SCOPE_IDENTITY();", Connections.pillboxDatabase);

                        command.Parameters.AddWithValue("@MEDICATIONID", medSchedule.MedicationId);
                        command.Parameters.AddWithValue("@NAME", medSchedule.Name);
                        command.Parameters.AddWithValue("@MEDINFO", medSchedule.MedInfo);
                        command.Parameters.AddWithValue("@EVERY", medSchedule.Every);
                        command.Parameters.AddWithValue("@COUNT", medSchedule.Count);
                        command.Parameters.AddWithValue("@DATE", temp.Date);
                        command.Parameters.AddWithValue("@HOUR", medSchedule.Hour);
                        command.Parameters.AddWithValue("@MINUTE", medSchedule.Minute);
                        command.Parameters.AddWithValue("@TAKEN", medSchedule.Taken);

                        Connections.pillboxDatabase.Open();

                        var medScheduleId = Convert.ToInt32(command.ExecuteScalar());
                        temp.Id = medScheduleId;
                        notificationSchedule.Add(temp);

                        Connections.pillboxDatabase.Close();

                        repeatNotification--;
                        if (repeatNotification == 0)
                        {
                            break;
                        }
                    }
                    daysWithNotification--;
                    date = date.AddDays(count); // mult by every?? e.g. * 7 for week
                }
            }
            catch (Exception ex)
            {
                return(BadRequest($"CreateMedicationSchedule() error \n {ex.ToString()}"));
            }
            finally
            {
                if (Connections.pillboxDatabase != null && Connections.pillboxDatabase.State == ConnectionState.Closed)
                {
                    Connections.pillboxDatabase.Close();
                }
            }

            //try
            //{
            //    foreach (var medSchedule in medicationSchedules)
            //    {
            //        var date = new DateTime();
            //        date = medSchedule.Date;
            //        for (int i = 0; i < repeatNotification; i++)
            //        {

            //            var temp = new MedicationSchedule();

            //            temp.Id = medSchedule.Id;
            //            temp.MedicationId = medSchedule.MedicationId;
            //            temp.Name = medSchedule.Name;
            //            temp.MedInfo = medSchedule.MedInfo;
            //            temp.Every = medSchedule.Every;
            //            temp.Count = medSchedule.Count;
            //            temp.Date = date;
            //            temp.Hour = medSchedule.Hour;
            //            temp.Minute = medSchedule.Minute;
            //            temp.Taken = medSchedule.Taken;

            //            var command = new SqlCommand("INSERT INTO MedicationSchedule (MEDICATIONID, NAME, MEDINFO, EVERY, COUNT, DATE, HOUR, MINUTE, TAKEN) " +
            //                "VALUES(@MEDICATIONID, @NAME, @MEDINFO, @EVERY, @COUNT, @DATE, @HOUR, @MINUTE, @TAKEN); SELECT SCOPE_IDENTITY();", Connections.pillboxDatabase);

            //            command.Parameters.AddWithValue("@MEDICATIONID", medSchedule.MedicationId);
            //            command.Parameters.AddWithValue("@NAME", medSchedule.Name);
            //            command.Parameters.AddWithValue("@MEDINFO", medSchedule.MedInfo);
            //            command.Parameters.AddWithValue("@EVERY", medSchedule.Every);
            //            command.Parameters.AddWithValue("@COUNT", medSchedule.Count);
            //            command.Parameters.AddWithValue("@DATE", temp.Date);
            //            command.Parameters.AddWithValue("@HOUR", medSchedule.Hour);
            //            command.Parameters.AddWithValue("@MINUTE", medSchedule.Minute);
            //            command.Parameters.AddWithValue("@TAKEN", medSchedule.Taken);

            //            Connections.pillboxDatabase.Open();

            //            var medScheduleId = Convert.ToInt32(command.ExecuteScalar());
            //            temp.Id = medScheduleId;
            //            notificationSchedule.Add(temp);
            //            date = date.AddDays(temp.Count); // mult by every?? e.g. * 7 for week

            //            Connections.pillboxDatabase.Close();
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    return BadRequest($"CreateMedicationSchedule() error \n {ex.ToString()}");
            //}
            //finally
            //{
            //    if (Connections.pillboxDatabase != null && Connections.pillboxDatabase.State == ConnectionState.Closed)
            //    {
            //        Connections.pillboxDatabase.Close();
            //    }
            //}
            return(notificationSchedule);
        }
        private async void GetData()
        {
            await Task.Run(async() =>
            {
                try
                {
                    await cancelPendingIntentsForMedicationSchedule();//_medications
                    string res = await WebServices.WebServices.Get($"{Constants.PublicServerAddress}/api/userMeds/{Utils.GetDefaults("Id")}", Utils.GetDefaults("Token"));

                    if (res != null)
                    {
                        Log.Error(Log_Tag, "RESULT_FOR_MEDICATIE" + res);
                        if (res.Equals("[]"))
                        {
                            return;
                        }
                        _medications = ParseResultFromUrl(res);
                        Log.Error(Log_Tag, "COUNT MEDICATIE " + _medications.Count);
                    }
                    else
                    {
                        Log.Error(Log_Tag, "res is null");
                    }
                }
                catch (Exception e)
                {
                    Log.Error(Log_Tag, "Alarm error " + e.Message);
                }
            });

            Log.Error(Log_Tag, _medications.Count + " _med list med count");

            if (_medications.Count != 0)
            {
                Log.Error(Log_Tag, "current count of medications from server " + _medications.Count);
                Log.Error(Log_Tag, "start showing what it's in medication list after received and parsed from server");
                foreach (MedicationSchedule item in _medications)
                {
                    Log.Error(Log_Tag, item.Title + ", " + item.Timestampstring + ", idNotification " + item.IdNotification + ", " + item.Postpone + ", UUID: " + item.Uuid);
                }
                Log.Error(Log_Tag, "the list is finished");



                var list = new List <MedicationSchedule>();

                for (var ms = 0; ms < _medications.Count; ms++)
                {
                    Log.Error(Log_Tag, _medications.Count + " in for");
                    bool x = await Storage.GetInstance().isHere(_medications[ms].Uuid);

                    Log.Error(Log_Tag, "is here? " + x);
                    if (x == false)
                    {
                        list.Add(_medications[ms]);
                        Log.Error(Log_Tag, "count of meds" + _medications.Count);
                        Log.Error(Log_Tag, "setting alarm for an uuid that does not exist in local db");
                        SetupAlarm(ms, _medications[ms].IdNotification);
                    }
                    else
                    {
                        Log.Error(Log_Tag, "so the uuid is here and start setting the alarm for them");
                        Log.Error(Log_Tag, "the item is: " + _medications[ms].Timestampstring + ", idNotification " + _medications[ms].IdNotification + ", " + _medications[ms].Postpone + ", UUID: " + _medications[ms].Uuid);

                        var      medDate     = Convert.ToDateTime(_medications[ms].Timestampstring);
                        DateTime currentDate = DateTime.Now;

                        if (medDate >= currentDate)
                        {
                            MedicationSchedule medObj = await Storage.GetInstance().getElementByUUID(_medications[ms].Uuid);

                            if (medObj.IdNotification == 0)
                            {
                                Log.Error(Log_Tag, "so the uuid is 0, I'm updating the PI'S id and set up alarm for the uuid " + _medications[ms].Uuid);
                                SetupAlarm(ms, _medications[ms].IdNotification);
                                Log.Error(Log_Tag, "UPDATED PI'S ID " + _medications[ms].IdNotification);
                                await Storage.GetInstance().removeMedSer(_medications[ms].Uuid);

                                await Storage.GetInstance().insertElementMedSer(_medications[ms]);

                                Log.Error(Log_Tag, "remove & insert element for pi's id != 0 and uuid already exists");
                            }
                            else
                            {
                                Log.Error(Log_Tag, "set alarm for uuid that is in local db, pi's id  " + medObj.IdNotification + " uuid " + medObj.Uuid);
                                SetupAlarm(ms, medObj.IdNotification);
                            }

                            Log.Error(Log_Tag, "setup alarm ");
                        }
                    }
                }

                await Storage.GetInstance().saveMedSer(list);

                Log.Error(Log_Tag, "saving this list.. ");
                foreach (var item in list)
                {
                    Log.Error(Log_Tag, "pi id " + item.IdNotification + " timestamp " + item.Timestampstring + " title  " + item.Title + " content " + item.Content + " uuit " + item.Uuid);
                }

                //test

                Log.Error(Log_Tag, "start reading what is saved in MedicineServerRecords .. ");
                var testList = await Storage.GetInstance().readMedSer();

                foreach (var item in testList)
                {
                    Log.Error(Log_Tag, "pi id " + item.IdNotification + " timestamp " + item.Timestampstring + " title  " + item.Title + " content " + item.Content + " uuit " + item.Uuid);
                }
                Log.Error(Log_Tag, "read is finished");
            }
            await Storage.GetInstance().deleteStinkyItems(_medications);
        }
Ejemplo n.º 28
0
        private async void UpdateDiseaseInLocalDbTask(Disease disease)
        {
            var listFromLocalDb = await ReadListFromDbPastDataTask();

            var listForCurrentDisease = listFromLocalDb.Where(c => c.Uuid.Contains("disease" + disease.Id));

            Log.Error("STORAGE class", "items for this disease");
            foreach (MedicationSchedule item in listForCurrentDisease)
            {
                Log.Error("STORAGE class", "item: " + item.ToString());
            }
            Log.Error("STORAGE class", "splitting items....");
            //----------------------------------------------- beta
            var list = new List <MedicationSchedule>();

            foreach (MedicationSchedule item in listFromLocalDb)
            {
                var    obj       = new MedicationSchedule(item.Uuid, item.Timestampstring, item.Title, item.Content, item.Postpone, item.IdNotification);
                string diseaseId = item.Uuid.Split("med")[0].Split("disease")[1];
                string medId     = item.Uuid.Split("med")[1].Split("hour")[0];
                string hourId    = item.Uuid.Split("med")[1].Split("hour")[1].Split("time")[0];
                string time      = item.Timestampstring;
                Log.Error("STORAGE class", "item splitted " + "disease: " + diseaseId + " medId: " + medId + " hourId: " + hourId + " time " + time);
                var isModified = false;
                if (disease.Id.Equals(diseaseId))
                {
                    foreach (Medicine med in disease.ListOfMedicines)
                    {
                        if (med.IdMed.Equals(medId))
                        {
                            foreach (Hour hour in med.Hours)
                            {
                                TimeSpan tspan = TimeSpan.Parse(hour.HourName);
                                var      dtMed = new DateTime(med.Date.Year, med.Date.Month, med.Date.Day, tspan.Hours, tspan.Minutes, tspan.Seconds);

                                if (hour.Id.Equals(hourId))
                                {
                                    if (time.Equals(dtMed.ToString()))
                                    {
                                        Log.Error("STORAGE class", "same datetime" + item.ToString());
                                    }
                                    DateTime dt = DateTime.Parse(time);
                                    if (!(dt.TimeOfDay.Equals(tspan)))
                                    {
                                        Log.Error("STORAGE class", "different hour" + item.ToString());
                                        obj = new MedicationSchedule("disease" + disease.Id + "med" + med.IdMed + "hour" + hour.Id + "time" + dtMed, dtMed.ToString(), disease.DiseaseName, med.Name, 5, 0);
                                        list.Add(obj);
                                        isModified = true;
                                    }
                                    else
                                    {
                                        Log.Error("STORAGE class", "same hour" + item.ToString());
                                    }
                                }
                                else
                                {
                                    Log.Error("STORAGE class", "different idHour");
                                    obj = new MedicationSchedule("disease" + disease.Id + "med" + med.IdMed + "hour" + hour.Id + "time" + dtMed, dtMed.ToString(), disease.DiseaseName, med.Name, 5, 0);
                                    list.Add(obj);
                                    isModified = true;
                                }
                            }
                        }
                    }
                }

                if (!isModified)
                {
                    list.Add(obj);
                }
            }

            Log.Error("STORAGE class", "new list");

            foreach (MedicationSchedule el in list)
            {
                Log.Error("STORAGE class", "item: " + el.ToString());
            }

            //----------------------------------------------- beta
        }