using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using TagLib;
using System;
using BangerTypes;
using UnityEngine.Networking;


namespace MenuAndSongs
{
	public class FindSongs
	{
		public static List<string> Find(string songPath)
		{
			if (!Directory.Exists(songPath))
				Directory.CreateDirectory(songPath);

			List<string> ls = Directory
				.GetFiles(songPath)
				.Where(file => Regex.IsMatch(file, ".*\\.rhys"))
				.ToList();

			return ls;
		}

		public static Song ParseRHYS(string rhysPath, Sprite defaultImage)
		{
			string jsonContent = System.IO.File.ReadAllText(rhysPath);
			Rhys rhys = JsonUtility.FromJson<Rhys>(jsonContent);

			string title = "<b>" + (rhys.title ?? "Title not found") + "</b>";
			string artist = string.IsNullOrEmpty(rhys.artist) ? "Artist not found" : "By: <b>" + rhys.artist + "</b>";
			string album = "Album information not available";

			TimeSpan duration = TimeSpan.FromSeconds(rhys.track_time);
			string formattedTimeSpan = string.Format("{0:D2}:{1:D2}:{2:D2}",
				(int)duration.TotalHours,
				duration.Minutes,
				duration.Seconds);

			Sprite coverImage;
			if (!string.IsNullOrEmpty(rhys.cover_art))
			{
				byte[] imageBytes = Convert.FromBase64String(rhys.cover_art);
				Texture2D texture = new Texture2D(2, 2);
				texture.LoadImage(imageBytes);
				coverImage = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
			}
			else
			{
				coverImage = defaultImage;
			}

			var notes = rhys.notes;

			return new Song
			{
				Title = title,
				Artist = artist,
				Album = album,
				DurationSpan = duration,
				Duration = formattedTimeSpan,
				CoverArt = coverImage,
				Notes = notes,
				Clip = LoadAudioFromBase64(rhys.audio)
			};
		}

		private static AudioClip LoadAudioFromBase64(string base64String)
		{
			byte[] mp3Bytes = Convert.FromBase64String(base64String);

			string tempFilePath = Path.Combine(Application.persistentDataPath, "tempMp3File.mp3");
			System.IO.File.WriteAllBytes(tempFilePath, mp3Bytes);

			AudioClip clip = LoadAudioSync(tempFilePath);

			System.IO.File.Delete(tempFilePath);

			return clip;
		}

		private static AudioClip LoadAudioSync(string filePath)
		{
			UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip("file://" + filePath, AudioType.MPEG);
			var operation = uwr.SendWebRequest();
			while (!operation.isDone)
				;  // Busy wait - not recommended

			if (uwr.result == UnityWebRequest.Result.Success)
			{
				return DownloadHandlerAudioClip.GetContent(uwr);
			}
			else
			{
				Debug.LogError("Error loading audio clip: " + uwr.error);
				return null;
			}
		}
	}
}
