using System;
using System.Linq;
using System.Text;

namespace Valg.EVA.Skanning.Scan.Startup
{
    public class EncodingGuard
    {
        private readonly IFileLoader fileLoader;
        
        
        
        
        
        
        
        
        
        
        private readonly Encoding[] disallowedEncodings = new Encoding[]
        {
            new UTF8Encoding(true)
        };

        public EncodingGuard(IFileLoader fileLoader)
        {
            this.fileLoader = fileLoader;
        }

        public void VerifyNoUTFBOMPresent(string[] pathsToFilesToVerify)
        {
            foreach (var path in pathsToFilesToVerify)
            {
                var bytes = fileLoader.GetBytes(path);
                ThrowExceptionIfBomInPreamble(path, bytes, disallowedEncodings);
            }
        }

        
        
        private void ThrowExceptionIfBomInPreamble(string path, byte[] bytes, Encoding[] encodingsToCheckFor)
        {
            foreach (var encoding in encodingsToCheckFor)
            {
                var bom = encoding.GetPreamble();
                var encodingHasBom = bom.Length > 0;
                if (encodingHasBom) 
                {
                    if (bytes.Zip(bom, (x, y) => x == y).All(x => x))
                    {
                        throw new InvalidOperationException($"File {path} is saved with an incompatible encoding: {encoding.EncodingName} with preamble/BOM: {encodingHasBom}");
                    }
                }
            }
        }
    }
}
