using System;
using System.Text;
using System.Runtime.InteropServices;

using size_t = System.UInt32;
using int32_t = System.Int32;
using ALLEGRO_FONT = System.IntPtr;

namespace sharpallegro5
{
    public class Allegro : AllegroApi
    {
        private static Random random;

        public static void srand(int seed)
        {
            random = new Random(seed);
        }

        public static int time(IntPtr timer)
        {
            if (timer == NULL)
            {
                return (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            }

            // TODO: should read the time_t structure pointed by ptr

            return -1;
        }

        public static int rand()
        {
            if (random == null) random = new Random();
            return random.Next();
        }

        public static void free(object o)
        {
            // NOOP
        }

        //new public static size_t al_utf8_encode(StringBuilder s, int32_t c)
        //{
        //    StringBuilder temp = new StringBuilder();
        //    size_t size = AllegroApi.al_utf8_encode(temp, c);

        //    if (size > 0)
        //    {
        //        s.Append((char)c);
        //    }

        //    return size;
        //}

        public static T PtrToStructure<T>(IntPtr ptr)
        {
            return (T)Marshal.PtrToStructure(ptr, typeof(T));
        }

        public static IntPtr StructureToPtr(object structure)
        {
            int size = Marshal.SizeOf(structure);
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(structure, ptr, false);
            return ptr;
        }

        #region Bitmap

        new public static ALLEGRO_LOCKED_REGION al_lock_bitmap(IntPtr bmp, int32_t format, int32_t flags)
        {
            return (ALLEGRO_LOCKED_REGION)Marshal.PtrToStructure(AllegroApi.al_lock_bitmap(bmp, format, flags), typeof(ALLEGRO_LOCKED_REGION));
        }

        #endregion

        #region System

        //new public static ALLEGRO_PATH al_get_standard_path(int id)
        //{
        //    IntPtr path = AllegroApi.al_get_standard_path(id);
        //    return (ALLEGRO_PATH)Marshal.PtrToStructure(path, typeof(ALLEGRO_PATH));
        //}

        #endregion

        #region Path

        //public static string al_path_cstr(ALLEGRO_PATH path, char delim)
        //{
        //    return AllegroApi.al_path_cstr(StructureToPtr(path), delim);
        //}

#endregion
    }
}
