/*
 * Copyright (c) 2020 Abex
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package net.runelite.http.api.gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.awt.Color;
import java.io.IOException;

public class ColorTypeAdapter extends TypeAdapter<Color>
{
	@Override
	public void write(JsonWriter out, Color value) throws IOException
	{
		if (value == null)
		{
			out.nullValue();
			return;
		}

		int rgba = value.getRGB();
		out.value(String.format("#%08X", rgba));
	}

	@Override
	public Color read(JsonReader in) throws IOException
	{
		switch (in.peek())
		{
			case NULL:
				in.nextNull();
				return null;
			case STRING:
			{
				String value = in.nextString();
				if (value.charAt(0) == '#')
				{
					value = value.substring(1);
				}
				int intValue = Integer.parseUnsignedInt(value, 16);
				return new Color(intValue, true);
			}
			case BEGIN_OBJECT:
			{
				in.beginObject();
				double value = 0;
				while (in.peek() != JsonToken.END_OBJECT)
				{
					switch (in.nextName())
					{
						case "value":
							value = in.nextDouble();
							break;
						default:
							in.skipValue();
							break;
					}
				}
				in.endObject();
				return new Color((int) value, true);
			}
		}
		return null; // throws
	}
}
