// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License

namespace Azure.Iot.Operations.EnvoyGenerator
{
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using Azure.Iot.Operations.CodeGeneration;

    internal class ResourceTransform : IEnvoyTemplateTransform
    {
        public const string LanguageResourcesFolder = "LanguageResources";
        public const string LanguageCommonFolder = "common";

        private const string CommonNsToken = "COMMON_NS";
        private const string SourceComment = "This file will be copied into the folder for generated code.";

        private readonly string destComment = $"Code generated by Azure.Iot.Operations.ProtocolCompilerLib v{Assembly.GetExecutingAssembly().GetName().Version}; DO NOT EDIT.";

        private readonly string resourceText;

        private static readonly Dictionary<TargetLanguage, Regex> namespaceReplacementRegexes = new()
        {
            { TargetLanguage.CSharp, new Regex(@"Azure\.Iot\.Operations\.Protocol\.UnitTests\.Serializers\.\w+") },
            { TargetLanguage.Rust, new Regex(@"resources") },
        };

        public ResourceTransform(TargetLanguage language, MultiCodeName commonNs, string projectName, string subFolder, string serializationPath, string serializationFile, string extension, string serializerCode, string srcSubdir)
        {
            string commonReplacement = commonNs.GetFolderName(language);
            string namespaceReplacement = commonNs.GetNamespaceName(language, projectName);

            this.FolderPath = Path.Combine(srcSubdir, serializationPath).Replace(CommonNsToken, commonReplacement);
            this.FileName = $"{serializationFile}.{extension}".Replace(CommonNsToken, commonReplacement);
            this.resourceText = namespaceReplacementRegexes[language].Replace(serializerCode, namespaceReplacement).Replace(CommonNsToken, commonReplacement).Replace(SourceComment, destComment);
        }

        public string FileName { get; }

        public string FolderPath { get; }

        public EndpointTarget EndpointTarget { get => EndpointTarget.Shared; }

        public string TransformText()
        {
            return this.resourceText;
        }
    }
}
