using System;
using System.IO;

namespace HWModules
{
    public static class FileSystemCheck
    {
        public static bool CheckSDCard()
        {
            var sd = SDStorage.Instance;
            const string tempDir = @"\SD\temp";
            const string tempFname = @"\SD\temp\fscheck";

            // Check for dir tmp
            if (Directory.Exists(tempDir) == false)
                Directory.CreateDirectory(tempDir);

            // Create a File in /SD/tmp
            const int msgSize = 10;
            var fileCheck = File.Create(tempFname, msgSize);

            // write a unique message 
            var random = new Random();
            var msg = new byte[msgSize];
            random.NextBytes(msg);
            fileCheck.Write(msg, 0, msg.Length);

            // close the file
            fileCheck.Close();

            //flush the file system
            sd.FlushBuffers();

            // reopen and read signature
            try
            {
                fileCheck = File.OpenRead(tempFname);
            }
            catch
            {
                return false;
            }

            var readMsg = new byte[msgSize];
            fileCheck.Read(readMsg, 0, msgSize);

            // close the file again
            fileCheck.Close();

            // compare the signatures
            for (int i=0; i < msgSize; i++)
            {
                if (readMsg[i] != msg[i])
                    return false;
            }

            return true;
        }

        public static void WriteManyBytes(int numwrites)
        {
            var sd = SDStorage.Instance;
            const string tempDir = @"\SD\temp";
            const string tempFname = @"\SD\temp\blob";

            // Check for dir tmp
            if (Directory.Exists(tempDir) == false)
                Directory.CreateDirectory(tempDir);

            // Create a File in /SD/tmp
            
            var fileCheck = File.Create(tempFname);

            // write a unique message 
            var random = new Random();
            var msg = new byte[65536];
            random.NextBytes(msg);
            for (int i= numwrites;i>0; --i)
                fileCheck.Write(msg, 0, msg.Length);

            // close the file
            fileCheck.Close();
        }
    }
}