/**************************************************************************************************

NetPolls - The web poll engine
Copyright (c) 2007 Data Illusion (http://www.dataillusion.com)

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.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using DataIllusion.NetPolls.DataAccess;
using DataIllusion.NetPolls.BusinessRules;
using DataIllusion.NetPolls.Data;
using DataIllusion.NetPolls.WebAdmin.UserControls;

namespace DataIllusion.NetPolls.WebAdmin
{
	/// <summary>
	/// Summary description for PollStats.
	/// </summary>
	public partial class QuestionEditor : PageBase
	{
		protected System.Web.UI.WebControls.DataGrid QuestionsDataGrid;
		protected HeaderControl PollHeader;

		protected void Page_Load(object sender, System.EventArgs e)
		{
			MessageLabel.Visible = false;

			_questionId = int.Parse(Request["questionid"]);

			if (!Page.IsPostBack)
			{
				PollHeader.PollId = PollId;
				
				// Generates Dropdownlist item list from 
				// the question layout enum
				QuestionLayoutEnum[] layouts  = (QuestionLayoutEnum[]) Enum.GetValues(typeof(QuestionLayoutEnum));
				for (int x = 0; x < layouts.Length; x++) 
				{
					ListItem listItem = new ListItem(layouts[x].ToString(),x.ToString());
					QuestionLayoutDropDownList.Items.Add(listItem);
				}

				BindData();
			}
		}

		private void BindData()
		{
			Questions questions = new Questions();
			QuestionData questionData = questions.GetQuestionById(_questionId); 
			QuestionTextBox.Text = questionData.Text;
			QuestionLayoutDropDownList.Items[Convert.ToInt32(questionData.Layout)].Selected = true;

			Answers answers = new Answers();
			AnswerDataCollection answerDataCollection = answers.GetAnswers(_questionId);
			AnswersDataGrid.DataKeyField = "Id";
			AnswersDataGrid.DataSource = answerDataCollection;
			AnswersDataGrid.DataBind();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.AnswersDataGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.AnswersDataGrid_CancelCommand);
			this.AnswersDataGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.AnswersDataGrid_EditCommand);
			this.AnswersDataGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.AnswersDataGrid_UpdateCommand);
			this.AnswersDataGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.AnswersDataGrid_DeleteCommand);

		}
		#endregion

		private void QuestionsRepeater_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
			Question question = new Question();
			question.DeleteQuestion(Convert.ToInt32(e.CommandArgument));
            Response.Redirect("PollBuilder.aspx?pollid="+PollId);	
		}

		protected void UpdateQuestionButton_Click(object sender, System.EventArgs e)
		{
			if (QuestionTextBox.Text.Length > 0)
			{
				Question question = new Question();
				QuestionData updatedQuestion = new QuestionData();
				updatedQuestion.Id = _questionId;
				updatedQuestion.Text = QuestionTextBox.Text;
				updatedQuestion.Layout = (QuestionLayoutEnum)Convert.ToInt32(QuestionLayoutDropDownList.SelectedItem.Value);
				question.UpdateQuestion(updatedQuestion);
				MessageLabel.Visible = true;
				MessageLabel.Text = "Question updated";
			}
			else
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = "Please enter some text for your question";
			}

		}

		protected void AddAnswerButton_Click(object sender, System.EventArgs e)
		{

			if (AnswerTextBox.Text.Length > 0)
			{
				Answer answer = new Answer();
				AnswerData newAnswer = new AnswerData();

				// Store the new answer in the database
				newAnswer.QuestionId = _questionId;
				newAnswer.Text = AnswerTextBox.Text;
				newAnswer.VoteCount = 0;
				answer.AddAnswer(newAnswer);
				AnswersDataGrid.EditItemIndex = -1; // Release edit mode
				BindData();
			}
			else
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = "Please enter some text for your answer";
			}
		}

		int _questionId = -1;

		private void AnswersDataGrid_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			AnswersDataGrid.EditItemIndex = -1; // Release edit mode
			BindData();
		}

		private void AnswersDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			Answer answer = new Answer();
			answer.DeleteAnswer(Convert.ToInt32(AnswersDataGrid.DataKeys[e.Item.ItemIndex]));
			AnswersDataGrid.EditItemIndex = -1; // Release edit mode
			BindData();		
		}

		private void AnswersDataGrid_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			AnswersDataGrid.EditItemIndex = e.Item.ItemIndex;
			BindData();
		}

		private void AnswersDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			AnswerData answerData = new AnswerData();
			Answer answer = new Answer();
			int voteTotal = 0;
			try
			{
				voteTotal = Convert.ToInt32(((TextBox) e.Item.Cells[1].Controls[0]).Text);

			}
			catch (FormatException)
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = "Total of votes must be numeric";
				return;
			}

			// Gets the Key id of the selected item and set
			// the updated values 
			answerData.Id = Convert.ToInt32(AnswersDataGrid.DataKeys[e.Item.ItemIndex]);
			answerData.Text = ((TextBox) e.Item.Cells[0].Controls[0]).Text;
			answerData.VoteCount = voteTotal;
			answer.UpdateAnswer(answerData);
			
			AnswersDataGrid.EditItemIndex = -1; // Release update mode
			BindData();
		}
	}
}
