using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Net;
using System.Security.Principal;
using Microsoft.Reporting.WebForms;
using eSecuritel.Utility;
using HITSWebService;

[PageSecurity(new HITSWebService.TaskType[] { HITSWebService.TaskType.ViewReports })]
public partial class site_Reports_ReportViewer : HITSPageBase
{
    /// <summary>
    /// Represents the different types of Reporting Service Report Parameters that might need to be accessed programatically
    /// </summary>
    private enum ParameterType
    {
        Carrier,
        Employee
    }

	protected void Page_Load(object sender, EventArgs e)
    {
        DebugTextBox.Visible = false;
	    try
	    {
            Page.Title = Resources.ReportsManagement.TitleEsecuritelColonUntitledReport;
            Page.MaintainScrollPositionOnPostBack = true;

            //Get Report Name from Query String        
            if (string.IsNullOrEmpty(Request[QueryStringKeys.ReportName]))
            {
                eSecuritel.Utility.HITSException hitsEx = new eSecuritel.Utility.HITSException("Invalid Report passed in to Report Viewer.");
                eSecuritel.Utility.HITSException.Log(hitsEx);
                throw hitsEx;
            }

            string sReportName = Request[QueryStringKeys.ReportName].ToString();
            string sReportTitle = Request[QueryStringKeys.ReportTitle].ToString();
            int sReportID = Convert.ToInt32(Request[QueryStringKeys.ReportID]);
            this.Page.Title = string.Format(Resources.ReportsManagement.TitleeSecuritelParameterReport, sReportTitle);

            //Don't initially show the report body.
            if (!Page.IsPostBack)
            {
                //ReportViewer1.ShowReportBody = false; 
                ReportViewer1.ServerReport.ReportServerCredentials = new MyReportServerCredentials();
                ReportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationContext.ReportServerURL);
                ReportViewer1.ServerReport.ReportPath = string.Format("/{0}/{1}", ConfigurationContext.ReportServerPath, sReportName);
                ReportViewer1.ServerReport.Timeout = int.Parse(ConfigurationContext.ReportingServicesTimeout);

                ReportParameterInfoCollection parameters = ReportViewer1.ServerReport.GetParameters();
                HITSMembershipUser user = HITSMembershipUser.GetUser();

                if (parameters != null)
                {
                    if (parameters["Locale"] != null)
                    {
                        ReportParameter location = new ReportParameter("Locale", SessionContext.CurrentRegion.LocaleData.ShortString);
                        location.Visible = false;
                        ReportViewer1.ServerReport.SetParameters(new ReportParameter[] { location });
                    }

                    try
                    {
                        //IT-9610: Need to make the Termed Subscriber Report in CA HITS work like US HITS
                        //Displaying only related companies to user in Carrier dropdown for RPT_TermedSubscribers report, exluded esecuritel users, they can see all companies
                        if ((sReportName == "RPT_TermedSubscribers" || sReportName == "RPT_FPCProgramReport") && parameters["OrganizationID"] != null && user.OrganizationId != 1)
                        {
                            ReportViewer1.ServerReport.SetParameters(new ReportParameter("OrganizationID", user.OrganizationId.ToString(), false));
                        }
                        
                        //used for segregation of reports
                        var reports = HITSWSDirector.GeneralManagementService.SelectReferenceVariables(RefControlEnum.SegregationReports).ToList();
                        if (ConfigurationContext.UseSegregationOfClients && HITSMembershipUser.GetAssignedCompanies().Any() && reports.Exists(r => r.RefName.Equals(sReportName)))
                        {
                            ReportViewer1.ServerReport.SetParameters(new ReportParameter("userID", user.UserId.ToString(), false));
                        }

                        ReportViewer1.ServerReport.Refresh();
                    }
                    catch (Exception ex)
                    {
                        HITSLog.WriteLog(String.Format("Error ocured while trying to set OrganizationID and userID report parameters, error: {0}", ex.Message));
                    }
                }

                //Restrict Carrier Parameter
                if ((user.OrganizationTypeId == (int)OrganizationManagement.OrganizationTypeId.Carrier) ||
                            (user.OrganizationTypeId == (int)OrganizationManagement.OrganizationTypeId.Dealer))
                    this.HideAndSetParameter(ParameterType.Carrier);

                SetAdditionalParameters(sReportName);

                ReportManagementService rms = null;

                try
                {
                    rms = HITSWSDirector.ReportManagementService;
                    rms.Open();

                    ReportLog rl = new ReportLog();
                    rl.CreatedByEmployeeID = user.UserId;
                    rl.ReportID = sReportID;
                    rl.ReportName = sReportTitle;
                    rl.ReportFileName = sReportName;

                    rms.InsertReportLog(rl);
                }
                catch (Exception ex)
                {
                    HITSException.Log(ex);
                }
                finally
                {
                    if (rms != null)
                    {
                        rms.Close();
                    }
                }
            } 
        }
        catch (Exception ex)
        {
            DebugTextBox.Text = Microsoft.Security.Application.Encoder.HtmlEncode("An error has occurred.");
            DebugTextBox.Visible = true;
            HITSException.Log(ex);
        }
    }

    private string GetExceptionMessages(Exception ex)
    {
        var message = string.Empty;
        var stackTrace = ex.StackTrace;
        while (ex != null)
        {
            message += ex.ToString();
            ex = ex.InnerException;
        }

        return string.Format("message: {0}, stacktrace:{1}", message, stackTrace);
    }

    protected void HITSReportsCalendar1_ShowCommand(object sender, HitsCommandEventArg e)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    private void SetAdditionalParameters(string reportName)
    {
        if (reportName.ToUpper().Contains("TRADEIN"))
        {
            var orderId = Request[QueryStringKeys.TradeInOrderId];
            if (!string.IsNullOrEmpty(orderId))
            {
                ReportViewer1.ServerReport.SetParameters(new ReportParameter("OrderID", orderId, false));
            }
        }
    }

    /// <summary>
    /// Hides and sets the reporting services report parameter to the appropriate value based on the passed in param enumeration.
    /// </summary>
    /// <param name="param"></param>
    private void HideAndSetParameter(ParameterType param)
    {
        //Force and Hide Carrier Parameter                 
        ReportParameter rp = null;
        ReportParameterInfoCollection rpic = ReportViewer1.ServerReport.GetParameters();
        HITSWebService.FulfillmentModel orgFulfillmentModel = OrganizationManagement.SelectOrgFufillmentModel(HITSMembershipUser.GetUser().OrganizationId);
        string rpiName = String.Empty;

        foreach (ReportParameterInfo rpi in rpic)
        {
            rpiName = rpi.Name.ToLower();
            switch (param)
            {
                case ParameterType.Carrier:
                    {
                        if ((rpiName == "carrier")
                            || (rpiName == "companyid"))
                        {
                            rp = new ReportParameter(rpi.Name, HITSMembershipUser.GetUser().OrganizationId.ToString());
                            rp.Visible = false;
                        }
                        else if (rpiName.Equals("aecompanyid"))
                        {
                            if (orgFulfillmentModel.Equals(HITSWebService.FulfillmentModel.Both)
                                || orgFulfillmentModel.Equals(HITSWebService.FulfillmentModel.DropShip))
                            {
                                rp = new ReportParameter(rpi.Name, HITSMembershipUser.GetUser().OrganizationId.ToString());
                            }
                            else
                            {
                                rp = new ReportParameter(rpi.Name,"0");
                            }
                            rp.Visible = false;
                        }
                        else if (rpiName.Equals("iscompanyid"))
                        {
                            if (orgFulfillmentModel.Equals(HITSWebService.FulfillmentModel.Both)
                                || orgFulfillmentModel.Equals(HITSWebService.FulfillmentModel.InStore))
                            {
                                rp = new ReportParameter(rpi.Name, HITSMembershipUser.GetUser().OrganizationId.ToString());
                            }
                            else
                            {
                                rp = new ReportParameter(rpi.Name, "0");
                            }

                            rp.Visible = false;
                        }
                        break;
                    }
                case ParameterType.Employee:
                    {
                        if (rpiName == "employee_id")
                        {
                            rp = new ReportParameter(rpi.Name, HITSMembershipUser.GetUser().UserId.ToString());
                            rp.Visible = false;
                            break;
                        }
                        break;
                    }
            }
          
        }

        if (rp != null)
            ReportViewer1.ServerReport.SetParameters(new ReportParameter[] { rp });
    }
}