[Back]

// DotNetNukeŽ - http://www.dotnetnuke.com
// Copyright (c) 2002-2009
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Services.Exceptions;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualBasic;

namespace AdefWebserver.Modules.SimpleSurvey
{
    public partial class Edit : DotNetNuke.Entities.Modules.PortalModuleBase
    {

        #region ViewState
        [Serializable]
        public class SurveyChoiceOption
        {
            public int SurveyChoiceID { get; set; }
            public string choice { get; set; }
        }

        public List<SurveyChoiceOption> SurveyChoices
        {
            get
            {
                if (ViewState["SurveyChoices"] == null)
                {
                    return new List<SurveyChoiceOption>();
                }
                else
                {
                    return (List<SurveyChoiceOption>)ViewState["SurveyChoices"];
                }
            }
            set
            {
                ViewState["SurveyChoices"] = value;
            }
        }
        #endregion

        int intSurveyQuestions = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    DisplaySurveyQuestions();
                }

                SetEditItemsVisibility();
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        #region DisplaySurveyQuestions
        private void DisplaySurveyQuestions()
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();
            var SurveyQuestions = from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                  where SurveyDataItems.ModuleID == ModuleId
                                  orderby SurveyDataItems.SortOrder ascending
                                  select SurveyDataItems;

            lvSurveyItems.DataSource = SurveyQuestions;
            intSurveyQuestions = SurveyQuestions.Count();

            lvSurveyItems.DataBind();
        }
        #endregion

        #region lnkBack_Click
        protected void lnkBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
        }
        #endregion

        #region SetEditItemsVisibility
        private void SetEditItemsVisibility()
        {
            if (
                ddlTypeInsert.SelectedValue == "Dropdown" ||
                ddlTypeInsert.SelectedValue == "Radio Buttons" ||
                ddlTypeInsert.SelectedValue == "Check Boxes"
                )
            {
                lnkInsertEditItems.Visible = true;
            }
            else
            {
                lnkInsertEditItems.Visible = false;
            }
        }
        #endregion

        #region lnkBackToQuestions
        protected void lnkBackToQuestions_Click(object sender, EventArgs e)
        {
            BackToQuestions();
        }
        #endregion

        #region BackToQuestions
        private void BackToQuestions()
        {
            pnlInsertEditQuestion.Visible = true;
            pnlInsertEditItems.Visible = false;
        }
        #endregion

        #region lnkEditItems_Click
        protected void lnkEditItems_Click(object sender, EventArgs e)
        {
            pnlInsertEditQuestion.Visible = false;
            pnlInsertEditItems.Visible = true;

            // Set the Question
            ListViewItem objListViewItem = (ListViewItem)lvSurveyItems.EditItem;
            TextBox DataNameTextBox = (TextBox)objListViewItem.FindControl("DataNameTextBox");
            lblQuestion.Text = String.Format("Question: {0}", DataNameTextBox.Text);

            // The Survey Choices were loaded when the Edit button for the row was clicked
            DisplaySurveyChoices();
        }
        #endregion

        #region lnkInsertEditItems_Click
        protected void lnkInsertEditItems_Click(object sender, EventArgs e)
        {
            pnlInsertEditQuestion.Visible = false;
            pnlInsertEditItems.Visible = true;

            lblQuestion.Text = String.Format("Question: {0}", "[New Question]");

            DisplaySurveyChoices();
        }
        #endregion

        #region DisplaySurveyChoices
        private void DisplaySurveyChoices()
        {
            lvSurveyChoices.DataSource = SurveyChoices;
            lvSurveyChoices.DataBind();
        }
        #endregion

        #region ddlTypeInsert_SelectedIndexChanged
        protected void ddlTypeInsert_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Reset Survey Choioces
            SurveyChoices = new List<SurveyChoiceOption>();

            // Take the ListVew out of Editmode and re-load it
            lvSurveyItems.EditIndex = -1;
            DisplaySurveyQuestions();
        }
        #endregion

        #region lvSurveyChoices_ItemInserting
        protected void lvSurveyChoices_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            ListViewItem objListViewItem = (ListViewItem)e.Item;
            TextBox objTextBox = (TextBox)objListViewItem.FindControl("choiceTextBox");

            SurveyChoiceOption objSurveyChoiceOption = new SurveyChoiceOption();
            objSurveyChoiceOption.SurveyChoiceID = 0;
            objSurveyChoiceOption.choice = objTextBox.Text.Replace(",", "");

            List<SurveyChoiceOption> tmpSurveyChoices = SurveyChoices;

            tmpSurveyChoices.Add(objSurveyChoiceOption);

            SurveyChoices = tmpSurveyChoices;

            DisplaySurveyChoices();
        }
        #endregion

        #region lvSurveyChoices_ItemDeleting
        protected void lvSurveyChoices_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            SurveyChoices.RemoveAt(e.ItemIndex);
            DisplaySurveyChoices();
        }
        #endregion

        #region InsertButton_Click
        protected void InsertButton_Click(object sender, EventArgs e)
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            // Get highest Sort Order
            var intHighestSortOrder = from DataItem in SimpleSurveyDataContext.SurveyDataItems
                                      where DataItem.ModuleID == ModuleId
                                      orderby DataItem.SortOrder
                                      select DataItem;

            // Insert the question
            SurveyDataItem objSurveyDataItem = new SurveyDataItem();
            objSurveyDataItem.DataName = DataNameTextBox.Text;
            objSurveyDataItem.Type = ddlTypeInsert.SelectedValue;
            objSurveyDataItem.ModuleID = ModuleId;
            objSurveyDataItem.Required = RequiredCheckBox.Checked;
            objSurveyDataItem.Visible = VisibleCheckBox.Checked;
            objSurveyDataItem.SortOrder = (intHighestSortOrder.FirstOrDefault() == null) ? 0 : Convert.ToInt32(intHighestSortOrder.Max(x => x.SortOrder).Value) + 1;

            SimpleSurveyDataContext.SurveyDataItems.InsertOnSubmit(objSurveyDataItem);
            SimpleSurveyDataContext.SubmitChanges();

            int SurveyDataItemID = objSurveyDataItem.SurveyDataItemID;

            if (SurveyChoices.Count > 0)
            {
                foreach (SurveyChoiceOption objSurveyChoiceOption in SurveyChoices)
                {
                    SurveyChoice objSurveyChoice = new SurveyChoice();
                    objSurveyChoice.SurveyDataItemID = SurveyDataItemID;
                    objSurveyChoice.choice = objSurveyChoiceOption.choice;

                    SimpleSurveyDataContext.SurveyChoices.InsertOnSubmit(objSurveyChoice);
                    SimpleSurveyDataContext.SubmitChanges();
                }
            }

            // Reset Insert line
            DataNameTextBox.Text = "";
            ddlTypeInsert.SelectedIndex = 0;

            BackToQuestions();
            DisplaySurveyQuestions();
        }
        #endregion

        // Delete Buttons and Sort Buttons

        #region lvSurveyItems_ItemCommand
        protected void lvSurveyItems_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            // Deleting
            if (e.CommandName == "Delete")
            {
                Button objButton = (Button)e.CommandSource;
                int intSurveyDataItemID = Convert.ToInt32(objButton.CommandArgument);

                SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

                // Get the Question
                var objDataItem = from DataItem in SimpleSurveyDataContext.SurveyDataItems
                                  where DataItem.SurveyDataItemID == intSurveyDataItemID
                                  select DataItem;

                // Get the SurveyChoices
                var colSurveyChoices = from SurveyChoices in SimpleSurveyDataContext.SurveyChoices
                                       where SurveyChoices.SurveyDataItemID == intSurveyDataItemID
                                       select SurveyChoices;

                // Get the Answers
                var colSurveyDataAnswers = from SurveyDataAnswers in SimpleSurveyDataContext.SurveyDataAnswers
                                           where SurveyDataAnswers.SurveyDataItemID == intSurveyDataItemID
                                           select SurveyDataAnswers;


                // Delete them all
                SimpleSurveyDataContext.SurveyDataItems.DeleteOnSubmit(objDataItem.FirstOrDefault());
                SimpleSurveyDataContext.SurveyChoices.DeleteAllOnSubmit(colSurveyChoices);
                SimpleSurveyDataContext.SurveyDataAnswers.DeleteAllOnSubmit(colSurveyDataAnswers);
                SimpleSurveyDataContext.SubmitChanges();

                DisplaySurveyQuestions();
            }

            // Sorting     
            if (e.CommandName == "Sort")
            {
                ListView objListView = (ListView)sender;
                // Only do this if we are not editing the ListView
                if (objListView.EditIndex == -1)
                {
                    int? intCurrentSortOrder = 0;
                    int intPreviousSurveyDataItemID = 0;
                    int intNextSurveyDataItemID = 0;

                    // Get Button information
                    ImageButton objImageButton = (ImageButton)e.CommandSource;
                    int intSurveyDataItemID = Convert.ToInt32(objImageButton.CommandArgument);

                    SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

                    //Get current SortID
                    intCurrentSortOrder = (from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                           where SurveyDataItems.SurveyDataItemID == intSurveyDataItemID
                                           select SurveyDataItems).FirstOrDefault().SortOrder;

                    if (objImageButton.ID == "imgUp")
                    {
                        //Up
                        intPreviousSurveyDataItemID = (from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                                       where SurveyDataItems.SortOrder < intCurrentSortOrder
                                                       orderby SurveyDataItems.SortOrder descending
                                                       select SurveyDataItems).FirstOrDefault().SurveyDataItemID;

                        SwitchQuestions(intSurveyDataItemID, intPreviousSurveyDataItemID);
                    }
                    else
                    {
                        //Down
                        intNextSurveyDataItemID = (from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                                   where SurveyDataItems.SortOrder > intCurrentSortOrder
                                                   orderby SurveyDataItems.SortOrder ascending
                                                   select SurveyDataItems).FirstOrDefault().SurveyDataItemID;

                        SwitchQuestions(intSurveyDataItemID, intNextSurveyDataItemID);
                    }

                    DisplaySurveyQuestions();
                }
            }

        }
        #endregion

        #region lvSurveyItems_ItemDeleting
        protected void lvSurveyItems_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            // This is handled in the lvSurveyItems_ItemCommand method
            e.Cancel = true;
        }
        #endregion

        #region lvSurveyItems_Sorting
        protected void lvSurveyItems_Sorting(object sender, ListViewSortEventArgs e)
        {
            // This is handled in the lvSurveyItems_ItemCommand method
            e.Cancel = true;
        }
        #endregion

        #region lvSurveyItems_ItemEditing
        protected void lvSurveyItems_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            ListView objListView = (ListView)sender;
            // Set the row to Edit mode
            objListView.EditIndex = e.NewEditIndex;

            // Set the dropdown on the Insert dropdown to Text so the 
            ddlTypeInsert.SelectedValue = "Text";
            // Set [Edit Items] link (on the Insert Line) so it will not show
            lnkInsertEditItems.Visible = false;

            DisplaySurveyQuestions();
        }
        #endregion

        #region lvSurveyItems_ItemCanceling
        protected void lvSurveyItems_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            ListView objListView = (ListView)sender;
            objListView.EditIndex = -1;
            DisplaySurveyQuestions();
        }
        #endregion

        #region lvSurveyItems_ItemUpdating
        protected void lvSurveyItems_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            ListView objListView = (ListView)sender;

            ListViewItem objListViewItem = (ListViewItem)objListView.EditItem;
            Label lblSurveyDataItemID = (Label)objListViewItem.FindControl("lblSurveyDataItemID");
            TextBox DataNameTextBox = (TextBox)objListViewItem.FindControl("DataNameTextBox");
            CheckBox RequiredCheckBox = (CheckBox)objListViewItem.FindControl("RequiredCheckBox");
            CheckBox VisibleCheckBox = (CheckBox)objListViewItem.FindControl("VisibleCheckBox");

            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            // Get the Question
            var objDataItem = (from DataItem in SimpleSurveyDataContext.SurveyDataItems
                               where DataItem.SurveyDataItemID == Convert.ToInt32(lblSurveyDataItemID.Text)
                               select DataItem).FirstOrDefault();

            // Update the Question
            objDataItem.DataName = Strings.Left(DataNameTextBox.Text, 200);
            objDataItem.Required = RequiredCheckBox.Checked;
            objDataItem.Visible = VisibleCheckBox.Checked;

            SimpleSurveyDataContext.SubmitChanges();

            // Delete all existing SurveyChoices
            var colSurveyChoices = from CurrentSurveyChoices in SimpleSurveyDataContext.SurveyChoices
                                   where CurrentSurveyChoices.SurveyDataItemID == Convert.ToInt32(lblSurveyDataItemID.Text)
                                   select CurrentSurveyChoices;

            SimpleSurveyDataContext.SurveyChoices.DeleteAllOnSubmit(colSurveyChoices);
            SimpleSurveyDataContext.SubmitChanges();

            // If there are SurveyChoices, add them
            if (SurveyChoices.Count > 0)
            {
                // Add all the SurveyChoices in the ViewState
                foreach (SurveyChoiceOption objSurveyChoiceOption in SurveyChoices)
                {
                    SurveyChoice objSurveyChoice = new SurveyChoice();
                    objSurveyChoice.SurveyDataItemID = Convert.ToInt32(lblSurveyDataItemID.Text);
                    objSurveyChoice.choice = objSurveyChoiceOption.choice;

                    SimpleSurveyDataContext.SurveyChoices.InsertOnSubmit(objSurveyChoice);
                    SimpleSurveyDataContext.SubmitChanges();
                }
            }

            objListView.EditIndex = -1;
            DisplaySurveyQuestions();
        }
        #endregion

        #region lvSurveyItems_ItemDataBound
        protected void lvSurveyItems_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            ListView objListView = (ListView)sender;

            // Only do this if we are editing the ListView
            if (objListView.EditIndex > -1)
            {
                // Only do this if we are editing this item
                if (e.Item.ID == objListView.EditItem.ID)
                {
                    Label TypeLabel = (Label)e.Item.FindControl("TypeLabel");
                    LinkButton lnkEditItems = (LinkButton)e.Item.FindControl("lnkEditItems");

                    // Show the Edit Items if this question has item choices
                    if (
                        TypeLabel.Text == "Dropdown" ||
                        TypeLabel.Text == "Radio Buttons" ||
                        TypeLabel.Text == "Check Boxes"
                        )
                    {
                        lnkEditItems.Visible = true;
                    }
                }
            }
            else
            {
                // We are not editing
                // Determine if the Sort buttons should show

                // If this item is the first item, hide the up button
                if (e.Item.ID == "ctrl0")
                {
                    ImageButton imgUp = (ImageButton)e.Item.FindControl("imgUp");
                    imgUp.ImageUrl = "~/DesktopModules/SimpleSurvey/Images/action_blank.gif";
                    imgUp.Enabled = false;
                }

                // If this item is the last item, hide the up down
                if (e.Item.ID == String.Format("ctrl{0}", (intSurveyQuestions - 1).ToString()))
                {
                    ImageButton imgDown = (ImageButton)e.Item.FindControl("imgDown");
                    imgDown.ImageUrl = "~/DesktopModules/SimpleSurvey/Images/action_blank.gif";
                    imgDown.Enabled = false;
                }
            }
        }
        #endregion

        #region lvSurveyItems_DataBound
        protected void lvSurveyItems_DataBound(object sender, EventArgs e)
        {
            ListView objListView = (ListView)sender;

            // Only load the SurveyChoices if the ListView is in Editing mode
            if (objListView.EditIndex > -1)
            {
                ListViewItem objListViewItem = (ListViewItem)lvSurveyItems.EditItem;
                Label lblSurveyDataItemID = (Label)objListViewItem.FindControl("lblSurveyDataItemID");

                SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

                List<SurveyChoice> colSurveyChoices = (from Survey_Choices in SimpleSurveyDataContext.SurveyChoices
                                                       where Survey_Choices.SurveyDataItemID == Convert.ToInt32(lblSurveyDataItemID.Text)
                                                       select Survey_Choices).ToList();

                List<SurveyChoiceOption> tmpSurveyChoices = new List<SurveyChoiceOption>();

                // Build SurveyChoices
                foreach (SurveyChoice objSurveyChoice in colSurveyChoices)
                {
                    SurveyChoiceOption objSurveyChoiceOption = new SurveyChoiceOption();
                    objSurveyChoiceOption.SurveyChoiceID = objSurveyChoice.SurveyChoiceID;
                    objSurveyChoiceOption.choice = objSurveyChoice.choice;
                    tmpSurveyChoices.Add(objSurveyChoiceOption);
                }

                // Set SurveyChoices
                SurveyChoices = tmpSurveyChoices;
            }
        }
        #endregion

        #region SwitchQuestions
        private void SwitchQuestions(int intSurveyDataItemID, int intOtherSurveyDataItemID)
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            var ExistingSurveyQuestion = (from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                          where SurveyDataItems.SurveyDataItemID == intSurveyDataItemID
                                          select SurveyDataItems).FirstOrDefault();

            var OtherSurveyQuestion = (from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                       where SurveyDataItems.SurveyDataItemID == intOtherSurveyDataItemID
                                       select SurveyDataItems).FirstOrDefault();

            int? ExistingSurveyQuestionSortOrder = ExistingSurveyQuestion.SortOrder;
            int? OtherSurveyQuestionSortOrder = OtherSurveyQuestion.SortOrder;

            ExistingSurveyQuestion.SortOrder = OtherSurveyQuestionSortOrder;
            OtherSurveyQuestion.SortOrder = ExistingSurveyQuestionSortOrder;

            SimpleSurveyDataContext.SubmitChanges();
        }
        #endregion

    }
}