//===============================================================================
// Microsoft patterns & practices
// Web Service Software Factory
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Xml;
using System.Globalization;

namespace Microsoft.Practices.SoftwareFactories.ServiceFactory.Actions.CodeDom.Helpers
{
    /// <summary/>
    public static class CodeProvider
    {
        /// <summary>
        /// Generates the code.
        /// </summary>
        /// <param name="codeCompileUnit">The code compile unit.</param>
        /// <param name="outputCodeFile">The output code file.</param>
        /// <param name="outputAssemblyFile">The output assembly file.</param>
        /// <param name="language">The language.</param>
        public static void GenerateCode(CodeCompileUnit codeCompileUnit, string outputCodeFile, string outputAssemblyFile, string language)
        {
            if (!String.IsNullOrEmpty(outputCodeFile))
            {
                using (TextWriter writer = new StreamWriter(outputCodeFile, true, new UTF8Encoding(true, true)))
                {
                    if (string.IsNullOrEmpty(language))
                    {
                        language = Path.HasExtension(outputCodeFile) ? 
                            CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(outputCodeFile)) : "C#";
                    }
                    CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(language);
                    CodeGeneratorOptions generatorOptions = new CodeGeneratorOptions();
                    generatorOptions.BracingStyle = "C";
                    codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, generatorOptions);
                    writer.Flush();

                    if (!String.IsNullOrEmpty(outputAssemblyFile))
                    {
                        CompilerParameters compilerParameters = new CompilerParameters();
                        compilerParameters.OutputAssembly = outputAssemblyFile;
                        AddStandardReferences(compilerParameters);

                        CompilerResults results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, new CodeCompileUnit[] { codeCompileUnit });

                        foreach (CompilerError error in results.Errors)
                        {
                            Console.WriteLine(error.ErrorText);
                        }

                        if (results.Errors.Count > 0)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.CompilationReturnErrors, results.Errors.Count));
                        }
                    }
                }
            }
        }

        private static void AddStandardReferences(CompilerParameters parameters)
        {
            //TODO: VERIFY
            //parameters.ReferencedAssemblies.Add(typeof(ServiceDescription).Assembly.Location);
            //parameters.ReferencedAssemblies.Add(typeof(XsdDataContractImporter).Assembly.Location);

            // Only for DataContract Imports.
            parameters.ReferencedAssemblies.Add(typeof(XmlElement).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(Uri).Assembly.Location);
        }
    }
}
