using System;
using System.Collections.Generic;
using System.IO;

namespace Webserver.FileCache {
	// Caching all files, useful for completely static folders only
	public class SimpleCache : AbstractCache {
		private readonly Dictionary<string, byte[]> fileCache = new Dictionary<string, byte[]> ();

		public override byte[] GetFileContent (string _filename) {
			try {
				lock (fileCache) {
					if (fileCache.TryGetValue(_filename, out byte[] content)) {
						return content;
					}

					if (!File.Exists (_filename)) {
						return null;
					}

					byte[] newContent = File.ReadAllBytes (_filename);
					fileCache.Add (_filename, newContent);

					return newContent;
				}
			} catch (Exception e) {
				Log.Out ($"Error in SimpleCache.GetFileContent: {e}");
			}

			return null;
		}

		public override (int, int) Invalidate () {
			(int, int) result = (0, 0);
			
			lock (fileCache) {
				result.Item1 = fileCache.Count;
				foreach ((string _, byte[] data) in fileCache) {
					result.Item2 += data.Length;
				}
				
				fileCache.Clear ();
			}

			return result;
		}
	}
}