// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using Microsoft.AspNetCore.Razor.Language.CodeGeneration;
using Microsoft.AspNetCore.Razor.Language.Intermediate;

namespace Microsoft.AspNetCore.Razor.Language
{
    internal class DefaultRazorCSharpLoweringPhase : RazorEnginePhaseBase, IRazorCSharpLoweringPhase
    {
        protected override void ExecuteCore(RazorCodeDocument codeDocument)
        {
            var documentNode = codeDocument.GetDocumentIntermediateNode();
            ThrowForMissingDocumentDependency(documentNode);

            var target = documentNode.Target;
            if (target == null)
            {
                var message = Resources.FormatDocumentMissingTarget(
                    documentNode.DocumentKind,
                    nameof(CodeTarget),
                    nameof(DocumentIntermediateNode.Target));
                throw new InvalidOperationException(message);
            }

            var writer = DocumentWriter.CreateDefault(documentNode.Target, documentNode.Options);
            var cSharpDocument = writer.WriteDocument(codeDocument, documentNode);
            codeDocument.SetCSharpDocument(cSharpDocument);
        }
    }
}
