using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using System.Collections.Generic;

public partial class Controls_Poll : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataBind();
    }

    protected void DataBind() {
        MSPoll _poll = MSPoll.GetPollByID(3);

        if (pnlVoteFields.Visible)
        {
            lblQuestion.Text = _poll.QuestionString;
            gvAnswers.DataSource = _poll.Answers;
            gvAnswers.DataBind();
        }
        else {
            gvResults.DataSource = _poll.Answers;
            gvResults.DataBind();
        }

    }
    protected void btnViewResults_click(object sender, EventArgs e)
    {
        pnlVoteResults.Visible = true;
        pnlVoteFields.Visible = false;

        DataBind();
    
    }

    protected void btnVote_Click(object sender, EventArgs e ) {

        string selectedValue = Request.Form["rbgVotes"];
        //int numberVotes = Int32.Parse(SqlHelper.ExecuteScalar(CommandType.Text, "SELECT count(ID) FROM PollVotes WHERE PollID = 3 AND AnswerID = " + selectedValue).ToString() + " AND User_IP = '" + Request.ServerVariables["REMOTE_ADDR"].ToString() + "'") );
        int numberVotes = 0;
        //if( !Utility.IsNull(Session["IP_ADDRESS"]) )
        //   numberVotes = Int32.Parse(SqlHelper.ExecuteScalar(CommandType.Text, "SELECT count(ID) FROM PollVotes WHERE PollID = 3  AND User_IP = '" + Session["IP_ADDRESS"].ToString() + "'").ToString() );
        
//        if ( numberVotes < 1)
        if( Utility.IsNull(Request.Cookies["Poll_3"] ) )
        {
            string ip_address = "";
            if (!Utility.IsNull(Session["IP_ADDRESS"]))
            {
                ip_address = Session["IP_ADDRESS"].ToString();
            }
            SqlHelper.ExecuteNonQuery(CommandType.Text, "INSERT INTO PollVotes ( PollID, AnswerID,User_IP ) VALUES( 3, " + selectedValue + ", '" + ip_address + "')");
            Response.Cookies.Add(new HttpCookie("Poll_3","true"));
        }
        pnlVoteResults.Visible = true;
        pnlVoteFields.Visible = false;

        DataBind();
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        pnlVoteResults.Visible = false;
        pnlVoteFields.Visible = true;
    
    }
}
