using System.Globalization;
using System.Text;
using System.Text.Json.Nodes;
namespace Febe.SitoDiProva;
///
/// The modules of the pages (issue #36, S4): a tiny registry of its own (__d to declare a module,
/// require to read it, an error for an unknown name) with the values a real site's page holds and the copy at
/// «Ho finito» reads — tokens, account, version fields, the doc_id of each GraphQL query. The names are the test
/// site's own (the page section of richieste.prova.json), never Instagram's; the values are the
/// constants the site checks in /api/.
///
public sealed partial class TestSite
{
/// The suffix of the module that exports the doc_id of a GraphQL query: ProvaProfiloQuery_operazioneProva.
public const string DocIdModuleSuffix = "_operazioneProva";
///
/// What the pages declare, by module and property, as text (numbers as the page would turn them into text); the
/// doc_id modules export the value itself (property "").
///
/// The id of the account the pages show as connected ().
public static IReadOnlyDictionary> PageModules(string accountId)
{
var modules = new Dictionary>(StringComparer.Ordinal);
foreach (var (name, module) in Modules(accountId))
{
modules[name] = module is JsonObject properties
? properties.ToDictionary(p => p.Key, p => Text(p.Value), StringComparer.Ordinal)
: new Dictionary(StringComparer.Ordinal) { [string.Empty] = Text(module) };
}
return modules;
}
/// The inline script of the registry, for the head of every page but the verification and session-ended ones.
internal static string ModuleRegistryScript(string accountId)
{
var text = new StringBuilder();
text.Append("");
return text.ToString();
}
/// Puts first in the head of .
internal static string InsertAfterHead(string html, string script)
{
var at = html.IndexOf("", StringComparison.Ordinal);
return at < 0 ? html : html.Insert(at + "".Length, script);
}
private static IEnumerable<(string Name, JsonNode Module)> Modules(string accountId)
{
yield return ("GettoniProva", new JsonObject { ["lsd"] = Lsd, ["dtsg"] = Dtsg });
yield return ("UtenteProva", new JsonObject { ["id"] = accountId, ["applicazione"] = AppId });
yield return ("VersioneProva", new JsonObject
{
["revisione"] = Revision,
["hs"] = HasteSession,
["hsi"] = HasteSessionId,
// Numbers in the page, as a real page keeps them: the copy turns them into text.
["dpr"] = int.Parse(Dpr, CultureInfo.InvariantCulture),
["comet"] = int.Parse(CometReq, CultureInfo.InvariantCulture),
});
yield return ("ConnessioneProva", new JsonObject { ["classe"] = ConnectionClass });
yield return ("AvvioProva", new JsonObject { ["nonce"] = EntryNonce });
foreach (var (operation, docId) in DocIds.OrderBy(d => d.Key, StringComparer.Ordinal))
{
yield return (operation + DocIdModuleSuffix, JsonValue.Create(docId));
}
}
private static string Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var number)
? number.ToString(CultureInfo.InvariantCulture)
: node?.GetValue() ?? string.Empty;
}