using System.IO;
using System.Threading;
using GHI.Usb.Host;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;

namespace HWModules
{
    public sealed class USBStorage
    {
        private static MassStorage USB;
        public AutoResetEvent evt = new AutoResetEvent(false);
        private static string sRootDirectory;

        private static USBStorage _instance;

        public static USBStorage Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new USBStorage();
                return _instance;
            }
        }

        private USBStorage()
        {
            RemovableMedia.Insert += new InsertEventHandler(Inserted);
            RemovableMedia.Eject += new EjectEventHandler(Ejected);

            Controller.MassStorageConnected += (sender, massStorage) =>
            {
                USB = massStorage;
                USB.Mount();
            };

            Controller.Start();

        }

        private void Inserted(object sender, MediaEventArgs e)
        {
            //Debug.Print("Insert event fired; USB Storage mount is finished.");
            if (e.Volume.IsFormatted)
            {
                sRootDirectory = e.Volume.RootDirectory;

                //Debug.Print("Available folders:");
                string[] strs = Directory.GetDirectories(e.Volume.RootDirectory);
                for (int i = 0; i < strs.Length; i++)
                    //Debug.Print(strs[i]);

                //Debug.Print("Available files:");
                strs = Directory.GetFiles(e.Volume.RootDirectory);
                for (int i = 0; i < strs.Length; i++)
                    Debug.Print(strs[i]);
            }
            else
            {
                //Debug.Print("Media is not formatted. Formatting...");
                e.Volume.Format("FAT", 0);
                sRootDirectory = e.Volume.RootDirectory;
            }
            evt.Set(); // proceed with other processing
        }

        private void Ejected(object sender, MediaEventArgs e)
        {
            //Debug.Print("Something Removed.");

        }
    }
}
