//--------------------------------------- DETAILS [GET] ------------------------------------------------------------------
        // GET: Question/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            /*OBS_QUESTION oBS_QUESTION = db.OBS_QUESTION.Find(id);
             if (oBS_QUESTION == null)
             {
                 return HttpNotFound();
             }
            return View(oBS_QUESTION);*/

            QuestionMDViewModel obsQMD = new QuestionMDViewModel((int)id);
            if (obsQMD == null)
            {
                return HttpNotFound();
            }
            return View(obsQMD);
        }
        public ActionResult QuestionAddUpdatePost(FormCollection postedData, QuestionMDViewModel QuestionMDView,
                                 [Bind(Prefix = "questn")] OBS_QUESTION questionHdr, string ans_type_list)
        {
            string posted_deleted_ids = postedData["obs_qat_Id_delList"];

            if (questionHdr.obs_question_eff_end_dt < Convert.ToDateTime("01/01/2000")) { questionHdr.obs_question_eff_end_dt = Convert.ToDateTime("12/31/2060"); }
            string posted_ans_type_list = postedData["ans_type_list"];//represents newly added selectable ans types
            string posted_existing_ans_type_data = postedData["sel_ans_list"]; //represents existing assigned ans types that need to be modified
            //string ans_type_list = "6~true~yes~no~maybe,10~false~1~2~3~4~5";
            //ans_type_list format: at_id~default~sel_ans,
            //                          6~ true  ~always~sometimes~never,
            //obs_qat_id_delList = qat_id,qat_id,... list of answer types to be deleted
            //-------- Save the Question Information ----
            int defaultQATid = -1;
            try
            {
                defaultQATid = Convert.ToInt32(postedData["defaultQATid"]);
            }
            catch { }
            using (DSC_OBS_DB_ENTITY db = new DSC_OBS_DB_ENTITY())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        
                        if(defaultQATid>0)
                        {
                            updateDefaultAnswerType(defaultQATid, "Y");
                        }
                        else if (questionHdr.obs_question_id > 0)
                        {             
                            List<OBS_QUEST_ANS_TYPES> temp_OBS_QUEST_ANS_TYPES = db.OBS_QUEST_ANS_TYPES.Where(x => x.obs_question_id == questionHdr.obs_question_id).ToList();
                            foreach(OBS_QUEST_ANS_TYPES x in temp_OBS_QUEST_ANS_TYPES )
                            {
                                x.obs_qat_default_ans_type_yn = "N";
                                db.SaveChanges();
                            }
                        }
                        ///////////////////////////////This section saves changes to existing answer types/////////////////////////////////
                        if (!string.IsNullOrEmpty(posted_existing_ans_type_data))
                        {
                            string[] split_ans_types_by = { "," };
                            string[] posted_single_ans_type_data = posted_existing_ans_type_data.Split(split_ans_types_by, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string str in posted_single_ans_type_data)
                            {
                                List<string> selAnsList_from_form = new List<string>();
                                string[] splitterm = { "~" };
                                string[] ans_type_elements = str.Split(splitterm, StringSplitOptions.RemoveEmptyEntries);
                                int intQATid = Convert.ToInt32(ans_type_elements[0]);
                                short obs_ans_type_id = db.OBS_QUEST_ANS_TYPES.Single(x => x.obs_qat_id == intQATid).obs_ans_type_id;
                                for (int i = 1; i < ans_type_elements.Length; i++)
                                {
                                    selAnsList_from_form.Add(ans_type_elements[i].Trim().ToUpper());
                                }
                                OBS_ANS_TYPE ans_type = db.OBS_ANS_TYPE.Single(item => item.obs_ans_type_id == obs_ans_type_id);
                                List<string> current_sel_ans_list = db.OBS_QUEST_SLCT_ANS.Where(item => item.obs_qat_id == intQATid && item.obs_qsa_eff_st_dt <= DateTime.Now && item.obs_qsa_eff_end_dt > DateTime.Now).Select(x => x.obs_qsa_text).ToList();                           
                                if (isEqualList(current_sel_ans_list, selAnsList_from_form, ans_type.obs_ans_type_category))
                                {//if we're here that means 2 lists are the same and we only need to change the order of selected answers list
                                        short order = 1;
                                        for (int i = 1; i < ans_type_elements.Length; i++)
                                        {
                                            string sel_ans_element = ans_type_elements[i];
                                            OBS_QUEST_SLCT_ANS oBS_QUEST_SLCT_ANS = db.OBS_QUEST_SLCT_ANS.Single(item => item.obs_qat_id == intQATid && item.obs_qsa_text == sel_ans_element && item.obs_qsa_eff_st_dt <= DateTime.Now && item.obs_qsa_eff_end_dt > DateTime.Now);
                                            oBS_QUEST_SLCT_ANS.obs_qsa_order = order;
                                            db.SaveChanges();
                                            order++;
                                        }
                                }
                                else//if we're here, that means user passed a different list of selected answers and we need to delete the current one and add new
                                {                                  
                                        //List<OBS_QUEST_SLCT_ANS> oBS_QUEST_SLCT_ANS = db.OBS_QUEST_SLCT_ANS.Where(item => item.obs_qat_id == intQATid).ToList();
                                        db.OBS_QUEST_SLCT_ANS.RemoveRange(db.OBS_QUEST_SLCT_ANS.Where(x => x.obs_qat_id == intQATid)); ;//update end effective date to todays date
                                        short order = 1;
                                        for (int i = 1; i < ans_type_elements.Length; i++)//now lets create a new record with updated selected answers
                                        {
                                            OBS_QUEST_SLCT_ANS UPDATED_oBS_QUEST_SLCT_ANS = new OBS_QUEST_SLCT_ANS();
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qat_id = intQATid;
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_text = ans_type_elements[i].ToUpper();
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_order = order;
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_wt = 1;
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_dflt_yn = "N";
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_eff_st_dt = DateTime.Now;
                                            UPDATED_oBS_QUEST_SLCT_ANS.obs_qsa_eff_end_dt = Convert.ToDateTime("12/31/2060");
                                            db.OBS_QUEST_SLCT_ANS.Add(UPDATED_oBS_QUEST_SLCT_ANS);
                                            order++;
                                        }// end foreach
                                       db.SaveChanges();                                                                      
                                }
                            }//foreach (string str in posted_single_ans_type_data)
                        }//end of  if (!string.IsNullOrEmpty(posted_existing_ans_type_data))
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                        //this section saves new question information or new question answer type
                        if (questionHdr.obs_question_id > 0)
                        {
                            OBS_QUESTION editedQuestion = db.OBS_QUESTION.Single(x => x.obs_question_id == questionHdr.obs_question_id);

                            if (!editedQuestion.obs_question_full_text.Equals(questionHdr.obs_question_full_text))
                            {
                                editedQuestion.obs_question_ver++;
                                
                            }                            
                            editedQuestion.obs_question_full_text = questionHdr.obs_question_full_text;
                            editedQuestion.obs_question_desc = questionHdr.obs_question_desc;
                            editedQuestion.obs_question_eff_st_dt = questionHdr.obs_question_eff_st_dt;
                            editedQuestion.obs_question_eff_end_dt = questionHdr.obs_question_eff_end_dt;
                            editedQuestion.obs_question_upd_dtm = DateTime.Now;
                            editedQuestion.obs_question_upd_uid = User.Identity.Name;
                            db.SaveChanges();
                        }
                        else {

                            if (questionHdr.obs_question_eff_end_dt < Convert.ToDateTime("01/01/1900"))
                            {
                                questionHdr.obs_question_eff_end_dt = Convert.ToDateTime("12/31/2060");
                            }
                            if (questionHdr.obs_question_eff_st_dt < Convert.ToDateTime("01/01/1900"))
                            {
                                questionHdr.obs_question_eff_st_dt = DateTime.Now;
                            }
                            questionHdr.obs_question_ver = 1;
                            questionHdr.obs_question_added_uid = User.Identity.Name;
                            questionHdr.obs_question_added_dtm = DateTime.Now;
                            db.OBS_QUESTION.Add(questionHdr);
                            db.SaveChanges();
                        }

                        if (!String.IsNullOrEmpty(posted_ans_type_list))
                        {
                            string[] splitter = { "," };
                            string[] passed_sel_ans_info = posted_ans_type_list.Split(splitter, StringSplitOptions.RemoveEmptyEntries);//all passed selectable answers data
                            foreach (string s in passed_sel_ans_info)
                            {
                                string[] splitby = { "~" };
                                string[] single_sel_ans_info = s.Split(splitby, StringSplitOptions.RemoveEmptyEntries);//individual answer type data
                                OBS_QUEST_ANS_TYPES new_assigned_ans_type = new OBS_QUEST_ANS_TYPES();
                                new_assigned_ans_type.obs_ans_type_id = Convert.ToInt16(single_sel_ans_info[0]);
                                new_assigned_ans_type.obs_question_id = questionHdr.obs_question_id;
                                new_assigned_ans_type.obs_qat_default_ans_type_yn = single_sel_ans_info[1] == "true" ? "Y" : "N";
                                db.OBS_QUEST_ANS_TYPES.Add(new_assigned_ans_type);
                                db.SaveChanges();//at this point we've saved the OBS_QUEST_ANS_TYPES record.
                                OBS_QUEST_ANS_TYPES passed_quest_ans_record = db.OBS_QUEST_ANS_TYPES.Single(x => x.obs_qat_id == new_assigned_ans_type.obs_qat_id);
                                if (passed_quest_ans_record.obs_qat_default_ans_type_yn != new_assigned_ans_type.obs_qat_default_ans_type_yn && new_assigned_ans_type.obs_qat_default_ans_type_yn == "N")
                                { //if existing record is default and we need to set it to N we need to do it here and we won't have to 
                                  //change any other records
                                    passed_quest_ans_record.obs_qat_default_ans_type_yn = "N";
                                    db.SaveChanges();
                                }
                                else if (passed_quest_ans_record.obs_qat_default_ans_type_yn != new_assigned_ans_type.obs_qat_default_ans_type_yn && new_assigned_ans_type.obs_qat_default_ans_type_yn == "Y")
                                {//  if passed qat_id needs to be default one, we should first set existing default to N and then update passed  to Y   
                                    try
                                    {
                                        int current_default_quest_id = db.OBS_QUEST_ANS_TYPES.Single(x => x.obs_question_id == passed_quest_ans_record.obs_question_id && x.obs_qat_id != passed_quest_ans_record.obs_qat_id && x.obs_qat_default_ans_type_yn == "Y").obs_question_id;
                                        setExistingDefaultToN(current_default_quest_id);
                                    }
                                    catch { }
                                    passed_quest_ans_record.obs_qat_default_ans_type_yn = "Y";
                                    db.SaveChanges();
                                }
                                if (single_sel_ans_info.Count() > 2)//now we need to check if there's selectable answers for this question
                                {
                                    short order = 1;
                                    for (int i = 2; i < single_sel_ans_info.Count(); i++)
                                    {
                                        OBS_QUEST_SLCT_ANS new_sel_ans = new OBS_QUEST_SLCT_ANS();
                                        new_sel_ans.obs_qat_id = new_assigned_ans_type.obs_qat_id;
                                        new_sel_ans.obs_qsa_text = single_sel_ans_info[i];
                                        new_sel_ans.obs_qsa_order = order;
                                        new_sel_ans.obs_qsa_wt = 1;
                                        new_sel_ans.obs_qsa_dflt_yn = "N";
                                        new_sel_ans.obs_qsa_eff_st_dt = DateTime.Now;
                                        new_sel_ans.obs_qsa_eff_end_dt = Convert.ToDateTime("12/31/2060");
                                        db.OBS_QUEST_SLCT_ANS.Add(new_sel_ans);
                                        db.SaveChanges();
                                        order++;
                                    }
                                }
                            }
                        }
                        ///////////////////////////////////WE DELETE SEL ANS HERE///////////////////////////////////////////
                        if (!string.IsNullOrEmpty(posted_deleted_ids))
                        {
                            string[] qats_to_delete = posted_deleted_ids.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string qat_to_delete in qats_to_delete)
                            {
                                deleteAssignedSelAns(Convert.ToInt32(qat_to_delete), db);
                            }
                        }
                        ///////////////////////////////////END OF DELETING SEL ANS///////////////////////////////////////////

                        // ------- Save the Question Metadata Changes ----
                        string MDlistBefore = postedData["origTags"];
                        string MDlistAfter = postedData["qAssignedMD"];
                        List<string> originalMDList = new List<string>();
                        List<string> newMDList = new List<string>();
                        if (!String.IsNullOrEmpty(MDlistBefore)) { originalMDList = MDlistBefore.Split(',').ToList(); }
                        if (!String.IsNullOrEmpty(MDlistAfter)) { newMDList = MDlistAfter.Split(',').ToList(); }
                        string[] mdIDsToDelete = originalMDList.Except(newMDList).ToArray();
                        string[] mdIDsToAdd = newMDList.Except(originalMDList).ToArray();

                        //---- Soft Delete all Metadata tags that are no longer used by the question
                        foreach (string deleteId in mdIDsToDelete)
                        {
                            int tempId = Convert.ToInt32(deleteId);
                            //int joitemp = db.OBS_QUEST_ASSGND_MD.Where(x => x.obs_quest_md_id == Convert.ToInt32(deleteId) && x.obs_question_id == questionHdr.obs_question_id).Select(x => x.obs_qad_id);
                            OBS_QUEST_ASSGND_MD oBS_QUEST_ASSGND_MD = db.OBS_QUEST_ASSGND_MD.FirstOrDefault(x => x.obs_quest_md_id == tempId && x.obs_question_id == questionHdr.obs_question_id);
                            oBS_QUEST_ASSGND_MD.obs_qad_eff_end_dt = DateTime.Today;
                            //db.OBS_QUESTION_METADATA.Remove(oBS_QUESTION_METADATA);  //No hard deletes
                        }

                        //---- Enable or Add the New metadata (MD) that will be assigned to the question ---
                        //-- Process each metadata entry to add for the selected question
                        foreach (string mdIdtoAdd in mdIDsToAdd)
                        {
                            try
                            {
                                int tempId = Convert.ToInt32(mdIdtoAdd);
                                //-- Look for an entry in OBS_QUEST_ASSGND_MD usign the Question Id and the metadata it.
                                OBS_QUEST_ASSGND_MD oBS_QUEST_ASSGND_MD = db.OBS_QUEST_ASSGND_MD.FirstOrDefault(x => x.obs_quest_md_id == tempId && x.obs_question_id == questionHdr.obs_question_id);
                                //-- If an entry is found in the junction table for that question, just enable it
                                if (oBS_QUEST_ASSGND_MD != null && tempId > 0)
                                {
                                    oBS_QUEST_ASSGND_MD.obs_qad_eff_end_dt = Convert.ToDateTime("12/31/2060");
                                }
                                else
                                { //-- If selected MD does not exist in the junction table for that question, add it.
                                    oBS_QUEST_ASSGND_MD = new OBS_QUEST_ASSGND_MD();
                                    oBS_QUEST_ASSGND_MD.obs_quest_md_id = tempId;
                                    oBS_QUEST_ASSGND_MD.obs_question_id = questionHdr.obs_question_id;
                                    oBS_QUEST_ASSGND_MD.obs_qad_eff_st_dt = DateTime.Today;
                                    oBS_QUEST_ASSGND_MD.obs_qad_eff_end_dt = Convert.ToDateTime("12/31/2060");
                                    db.OBS_QUEST_ASSGND_MD.Add(oBS_QUEST_ASSGND_MD);
                                }
                            }
                            catch { }
                        }

                        //---- Save All Changes ------
                        db.SaveChanges();

                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        string notused = e.Message;
                        transaction.Rollback();
                    }
                }


            }


            //ViewBag.ConfMsg = "Data Saved Successfully.";

            return RedirectToAction("QuestionAddUpdate", new {id = questionHdr.obs_question_id});

            //return RedirectToAction("Index", "Question");
            //return View("Edit");
        }
        //----------------------------------------------------------------


        //-----------------------------------------[ "EDIT"   Action: GET ] ---------------------------------------------------
        // GET: Question/Edit/5
        public ActionResult Edit(int id)
        {          
            QuestionMDViewModel obsQMD = new QuestionMDViewModel((int)id);
            if (obsQMD == null) {
                return HttpNotFound();
            }

            _listAnswerTypes((int)id);
            return View(obsQMD);
        }