using BangerTypes;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;


namespace UITypes
{
	public class SongEntry : Button
	{
		[UnityEngine.Scripting.Preserve]
		public new class UxmlFactory : UxmlFactory<SongEntry> { }

		public Song Song { get; set; }

		private MainMenu menu;

		public VisualElement InitEntry()
		{
			menu = GameObject.FindWithTag("MenuUI").GetComponent<MainMenu>();

			AddToClassList("songEntry");

			text = "";

			VisualElement contentWrapper = new();

			Image coverImage = new();
			VisualElement labelWrapper = new();

			Label titleLabel = new(), artistLabel = new(), albumLabel = new(), durationLabel = new();

			titleLabel.AddToClassList("SongEntryLabel");
			artistLabel.AddToClassList("SongEntryLabel");
			albumLabel.AddToClassList("SongEntryLabel");
			durationLabel.AddToClassList("SongEntryLabel");

			contentWrapper.AddToClassList("SongEntryContentWrapper");

			coverImage.AddToClassList("SongEntryCoverImage");
			coverImage.image = Song.CoverArt.texture;

			Song.AverageColor = GetAverage(Song.CoverArt);

			coverImage.style.backgroundColor = new StyleColor(Song.AverageColor);

			labelWrapper.AddToClassList("SongEntryLabelWrapper");

			titleLabel.text = Song.Title;
			artistLabel.text = Song.Artist;
			albumLabel.text = Song.Album;
			durationLabel.text = Song.Duration;

			this.Add(contentWrapper);

			labelWrapper.Add(titleLabel);
			labelWrapper.Add(artistLabel);
			labelWrapper.Add(albumLabel);
			labelWrapper.Add(durationLabel);

			contentWrapper.Add(coverImage);
			contentWrapper.Add(labelWrapper);

			RegisterCallback<ClickEvent>(LoadSong);

			return this;
		}

		public void LoadSong(ClickEvent evt)
		{
			menu.PlaySong(this);
		}

		Color32 GetAverage(Sprite image)
		{
			Color32[] pixels = image.texture.GetPixels32();

			int totalR = 0;
			int totalG = 0;
			int totalB = 0;

			foreach (Color32 pixel in pixels)
			{
				totalR += pixel.r;
				totalG += pixel.g;
				totalB += pixel.b;
			}

			int pixelCount = pixels.Length;
			int averageR = totalR / pixelCount;
			int averageG = totalG / pixelCount;
			int averageB = totalB / pixelCount;

			Color averageColor = new Color32((byte)averageR, (byte)averageG, (byte)averageB, 255);

			return averageColor;
		}
	}
}
