module swizzle;
import std.stdio, std.conv;
import std.traits, std.algorithm;

private enum properties = ["xyzw", "rgba"];

private template indexOfProperty(char c, size_t i=0)
{
    static assert(properties.length > 0, "property list empty");

    static if(countUntil(properties[i], c) != -1)
        enum size_t indexOfProperty = countUntil(properties[i], c);
    else static if(i < properties.length - 1)
        enum size_t indexOfProperty = indexOfProperty!(c, i + 1);
    else static assert(0, "unable to locate index: " ~ c);
}

private template isPropertiesSorted(string s, size_t i=0)
{
    static if(countUntil(properties[i], s) != -1)
        enum isPropertiesSorted = true;
    else static if(i < properties.length - 1)
        enum isPropertiesSorted = isPropertiesSorted!(s, i + 1);
    else
        enum isPropertiesSorted = false;
}

void swizzleCopy(string s, size_t i, size_t AN, size_t BN, A, B)(ref A a, ref const B b)
{
	enum ai = i-1;
	enum bi = indexOfProperty!(s[ai]);

	static assert(ai < AN, s[ai] ~ ": index out of bounds A " ~to!string(ai)~ " >= " ~to!string(AN));
	static assert(bi < BN, s[ai] ~ ": index out of bounds B " ~to!string(bi)~ " >= " ~to!string(BN));

	a[ai] = b[bi];
	
	static if(i > 1)
		swizzleCopy!(s, ai, AN, BN)(a, b);
}

private struct Vtest(T, size_t N) {
	
	this(T a) {
		foreach(ref e; raw)
			e = a += 1;
	}
	
	template opDispatch(string s)
	{
		static if(isPropertiesSorted!s)
		{
			ref auto opDispatch()
			{
				enum index = indexOfProperty!(s[0]);
				static assert(index + s.length <= N, "index out of bounds");

				return *(cast(Vtest!(T, s.length)*)
					&raw.ptr[index]);
			}
		}
		else
		{
			auto opDispatch()
			{
				Vtest!(T, s.length) r;
				swizzleCopy!(s, s.length, s.length, N)(r.raw, raw);
				return r;
			}
		}
	}


	T[N] raw;
}

template swizzle(string s)
{
	static if(isPropertiesSorted!s)
	{
		ref auto swizzle(size_t N, T)(ref T[N] arg)
		{
			enum index = indexOfProperty!(s[0]);
			static assert(index + s.length <= N, "index out of bounds");

			return *(cast(T[s.length]*)
				&arg.ptr[index]);
		}
	}
	else
	{
		auto swizzle(size_t N, T)(const ref T[N] arg)
		{
			T[s.length] r;
			swizzleCopy!(s, s.length, s.length, N)(r, arg);
			return r;
		}
	}
}

private void test()
{
	alias Vtest!(float, 3) V3;
	alias Vtest!(float, 4) V4;
	alias Vtest!(float, 5) V5;

	V3 a = V3(3);
	V4 b = V4(13);
	V5 c = V5(42);

	float[3] aa = [4.0f, 5, 6];
	float[4] bb = [14.0f, 15, 16, 17];
	float[5] cc = [43.0f, 44, 45, 46, 47];

	writeln(a.raw);
	writeln(b.raw);
	writeln(c.raw);
	writeln(aa);
	writeln(bb);
	writeln(cc);
	writeln("-----");

	b.xyz = a.gbr;
	c.zw  = a.rb;

	swizzle!"xyz"(bb) = swizzle!"gbr"(aa);
	swizzle!"zw"(cc)  = swizzle!"rb"(aa);

	writeln(a.raw);
	writeln(b.raw);
	writeln(c.raw);
	writeln(aa);
	writeln(bb);
	writeln(cc);
}

void main()
{
	test();
}
