using System;
using System.Collections.Generic;
using System.Text;
using nft.framework.drawing;
using System.IO;
using System.Drawing;
using System.Runtime.Serialization;

namespace nft.framework.util {
    public class LocalFileImageRef : FileImageRef {
        static private readonly Dictionary<String, LocalFileImageRef> pathlist
            = new Dictionary<String, LocalFileImageRef>();

        public readonly string path;

        private LocalFileImageRef(string id) {
            this.path = id;
        }

        public override string FullPath { get { return path; } }

        /// <summary>
        /// Get or create ImageRef object for an image specifed by the file path
        /// Caller do not need to call first 'IncreaseRefCount'
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static ImageRef FromFile(string filename) {
            string path = Path.GetFullPath(filename);
            LocalFileImageRef refObj = null;
            if (!pathlist.TryGetValue(path, out refObj)) {
                refObj = new LocalFileImageRef(path);
                pathlist.Add(path, refObj);
            }
            return refObj;
        }

        public static void FreeIsolatedImages() {
            List<string> work = new List<string>();
            foreach (string key in pathlist.Keys) {
                LocalFileImageRef ir = pathlist[key];
                if (ir.RefCount == 0) {
                    ir.ForceDispose();
                    work.Add(key);
                }
            }
            foreach (string key in work) {
                pathlist.Remove(key);
            } 
        }
    }
}
