﻿using System;
using System.Collections.Generic;
using System.IO;
using Oni.Imaging;

namespace Oni.Motoko
{
    internal static class TextureUtils
    {
        public static SurfaceFormat ToSurfaceFormat(this TextureFormat format)
        {
            switch (format)
            {
                case TextureFormat.BGRA4444:
                    return SurfaceFormat.BGRA4444;

                case TextureFormat.BGR555:
                    return SurfaceFormat.BGRX5551;

                case TextureFormat.BGRA5551:
                    return SurfaceFormat.BGRA5551;

                case TextureFormat.RGBA:
                    return SurfaceFormat.RGBA;

                case TextureFormat.BGR:
                    return SurfaceFormat.BGRX;

                case TextureFormat.DXT1:
                    return SurfaceFormat.DXT1;

                default:
                    throw new NotSupportedException(string.Format("Texture format {0} is not supported", format));
            }
        }

        public static Surface LoadImage(string filePath)
        {
            var surfaces = new List<Surface>();

            switch (Path.GetExtension(filePath).ToLowerInvariant())
            {
                case ".tga":
                    surfaces.Add(TgaReader.Read(filePath));
                    break;
                default:
#if !NETCORE
                    surfaces.Add(SysReader.Read(filePath));
#endif
                    break;
            }

            if (surfaces.Count == 0)
                throw new InvalidDataException(string.Format("Could not load image '{0}'", filePath));

            return surfaces[0];
        }

        public static int RoundToPowerOf2(int value)
        {
            if (value <= 2)
                return value;

            int hsb = 0;

            for (int x = value; x > 1; hsb++)
                x >>= 1;

            //
            // TODO would be nice to round up for cases like 127
            // But that require to upscale the image and currently the image
            // resizing code doesn't handle upscaling.
            //

            //return 1 << (hsb + ((value >> (hsb - 1)) & 1));

            return 1 << hsb;
        }
    }
}
