using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using C1.C1Report;

namespace ReportViewerWithC1Report.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class C1ReportService
    {
        /// <summary>
        /// Get a list of the reports available on the server.
        /// </summary>
        [OperationContract]
        public string[] GetReportList()
        {
            var fn = GetReportDefinitionFile();
            return C1Report.GetReportList(fn);
        }
        /// <summary>
        /// Get a PDF stream containing the specified report.
        /// </summary>
        [OperationContract]
        public byte[] GetReport(string reportName)
        {
            // make sure the requested report exists
            if (!GetReportList().Contains(reportName))
            {
                throw new Exception("The report requested was not found in the report definition file.");
            }

            // load report
            var c1r = new C1Report();
            var fn = GetReportDefinitionFile();
            c1r.Load(fn, reportName);

            // adjust connection string to point to our data source (c1nwind.mdb)
            c1r.DataSource.ConnectionString = GetConnectionString();
            foreach (Field f in c1r.Fields)
            {
                // adjust subreports too (one level deep, this is just a sample)
                if (f.Subreport != null)
                {
                    f.Subreport.DataSource.ConnectionString = GetConnectionString();
                }
            }

            // export to pdf
            using (var ms = new MemoryStream())
            {
                c1r.RenderToStream(ms, FileFormatEnum.PDF);
                return ms.ToArray();
            }
        }

        // report definition file is deployed with the app
        static string GetReportDefinitionFile()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CommonTasks.xml");
        }

        // connection string refers to C1 sample mdb file
        static string GetConnectionString()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\ComponentOne Samples\Common";
            string conn = @"provider=microsoft.jet.oledb.4.0;data source={0}\c1nwind.mdb;";
            return string.Format(conn, path);
        }
    }
}
