using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Configuration;
using System.ServiceModel;
using System.Text;
using UMinho.GestaoProjectos.RSExecution;
using System.Net;

namespace UMinho.GestaoProjectos
{
    public class PrintServices
    {
        private static string _reportService = null;
        private static string _rptUID = null;
        private static string _rptPwd = null;
        private static string _rptFormat = null;

        public PrintServices()
        {
          
        }

        public byte[] PrintGenericReport(string Config, string ReportName, string FileName, bool ExportaExcel, bool ExportaWord, bool autoDownload, object[] _params)
        {

            #region Reporting Services Settings
            NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection(Config);
            string _rptName = (section[ReportName].Split('?'))[0];
            _reportService = section["ReportServer"];
            _rptUID = section["RptUID"];
            _rptPwd = section["RptPwd"];
            _rptFormat = section["RptFormat"];

            string formatoExport  = _rptFormat;
            if (ExportaExcel)
            {
                formatoExport = "Excel";
            }
            if (ExportaWord)
            {
                formatoExport = "Word";
            }

           
            RSExecution.ReportExecutionService rs = new RSExecution.ReportExecutionService();
            rs.Url = _reportService;
            rs.Credentials = new NetworkCredential(_rptUID, _rptPwd);
            string margins = string.Empty;
            if (section["RptMarginTop"] != null)
            {
                margins = 
                    "  <MarginTop>" + section["RptMarginTop"] + "</MarginTop>" +
                    "  <MarginLeft>" + section["RptMarginLeft"] + "</MarginLeft>" +
                     "  <MarginRight>" + section["RptMarginRight"] + "</MarginRight>" +
                    "  <MarginBottom>" + section["RptMarginBottom"] + "</MarginBottom>";
            }
            string _RptDeviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>" + formatoExport + "</OutputFormat>" + margins + "</DeviceInfo>";
           
          
            string _RptHistoryId = null;

            #endregion

            #region parâmetros do report

            RSExecution.ParameterValue[] parameters = null;
            if (_params != null && _params.Count() > 0)
            {
                parameters = new RSExecution.ParameterValue[_params.Length];

                string sparams = String.Format(section[ReportName], _params);
                int indexInterrogacao = sparams.IndexOf('?');
                string[] _str_params = sparams.Substring(indexInterrogacao + 1).Split('&');


                for (int i = 0; i < _str_params.Length; i++)
                {
                    string s = null;
                    parameters[i] = new RSExecution.ParameterValue();
                    string[] __sp = _str_params[i].ToString().Split('=');
                    parameters[i].Name = __sp[0];
                    
                    parameters[i].Value = __sp[1].Length == 0 ? s : __sp[1];
                }
            }

            #endregion

            #region Render do Report

            // parametros de output
            string _RptEncoding;
            string _RptMimeType;
            string _RptExtention;
            RSExecution.Warning[] _RptOptionalWarnings = null;
            string[] _RptStreamIdentifiers;
            rs.LoadReport(_rptName, _RptHistoryId);
            if (parameters != null)
            {
                rs.SetExecutionParameters(parameters, "pt-PT");
            }
            // render do report
            byte[] result = rs.Render(formatoExport, _RptDeviceInfo,
                out _RptExtention,out _RptMimeType, out _RptEncoding, out _RptOptionalWarnings, out _RptStreamIdentifiers);
            if (autoDownload)
            {

                try
                {
                    // output do report
                    HttpResponse _RptResponse = HttpContext.Current.Response;
                    //_RptResponse.ClearHeaders();
                    //_RptResponse.ClearContent();
                    _RptResponse.Clear();
                    _RptResponse.ContentType = _RptMimeType;
                    if (_RptEncoding != null) _RptResponse.ContentEncoding = Encoding.GetEncoding(_RptEncoding);


                    // construir o nome do ficheiro pdf
                    string _FileName = FileName.Substring(0, Math.Min(FileName.Length, 100));
                    _FileName = System.Web.HttpUtility.UrlEncode(_FileName.Replace(' ', '_'));
                    if (ExportaExcel)
                        _RptResponse.AddHeader("Content-Disposition", String.Format("attachment; FileName=\"{0}.xls\"", _FileName));
                    else
                    {
                        if (ExportaWord)
                            _RptResponse.AddHeader("Content-Disposition",String.Format("attachment; FileName=\"{0}.doc\"", _FileName));
                        else
                            _RptResponse.AddHeader("Content-Disposition", String.Format("attachment; FileName=\"{0}.{1}\"", _FileName, _RptMimeType.Split(new char[] { '/' })[1]));
                    }
                    
                    _RptResponse.OutputStream.Write(result, 0, result.Length);
                    _RptResponse.Flush();
                    try
                    {
                        _RptResponse.End();
                    }
                    catch  
                    {
                        
                        
                    }

                }
                catch (System.Threading.ThreadAbortException)
                {

                }
            }
            return result;
            #endregion


        }

        
    }
}