using System;
using System.IO;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using GHI.Premium.IO;

namespace CPF
{
    public class Media
    {
        private PersistentStorage _sdCard;

        public Media()
        {
            _sdCard = null;
        }

        public void Start()
        {
            RemovableMedia.Insert += new InsertEventHandler(RemovableMedia_Insert);
            RemovableMedia.Eject += new EjectEventHandler(RemovableMedia_Eject);
            new Thread(SD_Card_Observer).Start();
        }

        public static void Stop()
        {
        }
     
        private void RemovableMedia_Eject(object sender, MediaEventArgs e)
        {
            Debug.Print("SD card ejected");
        }
     
        private void RemovableMedia_Insert(object sender, MediaEventArgs e)
        {
            Debug.Print("SD card inserted");
     
            if (e.Volume.IsFormatted)
            {
            }
            else
            {
                Debug.Print("SD card is not formatted");
            }
        }
     
        private void SD_Card_Observer()
        {
            _sdCard = null;
            const int POLL_TIME = 500; // check every 500 millisecond

            bool sdCardInserted;
            while (true)
            {
                try // If SD card was removed while mounting, it may throw exceptions
                {
                    sdCardInserted = PersistentStorage.DetectSDCard();
     
                    // make sure it is fully inserted and stable
                    if (sdCardInserted)
                    {
                        Thread.Sleep(100);
                        sdCardInserted = PersistentStorage.DetectSDCard();
                    }
                    if (sdCardInserted && _sdCard == null)
                    {
                        _sdCard = new PersistentStorage("SD");
                        _sdCard.MountFileSystem();
                    }
                    else if (!sdCardInserted && _sdCard != null)
                    {
                        _sdCard.UnmountFileSystem();
                        _sdCard.Dispose();
                        _sdCard = null;
                    }
                }
                catch
                {
                    if (_sdCard != null)
                    {
                        _sdCard.Dispose();
                        _sdCard = null;
                    }
                }
     
                Thread.Sleep(POLL_TIME);
            }
        }
    }
}

