﻿using System;
using System.Collections.Generic;
using Oni.Imaging;

namespace Oni.Motoko
{
    internal class Texture
    {
        public readonly List<Surface> Surfaces = new List<Surface>();
        public int Width;
        public int Height;
        public TextureFormat Format;
        public TextureFlags Flags;
        public string Name;
        public Texture EnvMap;

        public void GenerateMipMaps()
        {
            if ((Flags & TextureFlags.HasMipMaps) != 0)
                return;

            var surface = Surfaces[0];

            Surfaces.Clear();
            Surfaces.Add(surface);

            if (surface.Format == SurfaceFormat.DXT1)
                surface = surface.Convert(SurfaceFormat.BGRX5551);

            int width = surface.Width;
            int height = surface.Height;
            var surfaceFormat = Format.ToSurfaceFormat();

            while (width > 1 || height > 1)
            {
                width = Math.Max(width >> 1, 1);
                height = Math.Max(height >> 1, 1);

                surface = surface.Resize(width, height);

                Surfaces.Add(surface);
            }

            if (surface.Format != surfaceFormat)
            {
                for (int i = 1; i < Surfaces.Count; i++)
                    Surfaces[i] = Surfaces[i].Convert(surfaceFormat);
            }

            Flags |= TextureFlags.HasMipMaps;
        }

        public bool HasAlpha => Surfaces[0].HasAlpha;

        public bool WrapU => (Flags & TextureFlags.NoUWrap) == 0;
        public bool WrapV => (Flags & TextureFlags.NoVWrap) == 0;
    }
}
