@model User
@using Newtonsoft.Json
@using System.Text
@{
    ViewData["Title"] = "User details";
}

<a href="/">home</a>/@Html.Raw(ViewData["breadcrumbs"])
<table class="table">
    <tbody>
        <tr>
            <th scope="row">Display Name (here)</th>
            <td><input type="text" id="displayName" value="@Model.DisplayName" disabled alt="todo"></input> <button
                    onclick="patchModel(jsonifyUser(), @Html.Raw("'/api/Users/'"))" disabled alt"todo">update</button></td>
        </tr>
        <tr>
            <th scope="row">Accounts</th>
            <td>
                <div id="accountsTree"></div>
            </td>
        </tr>
   </tbody>
</table>

@section Scripts{

    <script type="text/javascript">
        @{
            var userAsString = JsonConvert.SerializeObject(Model, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
        }
          const userOnLoad = @Html.Raw(userAsString);
        function jsonifyUser() {
            var userNow = structuredClone(userOnLoad);
            userNow.Accounts = null;
            userNow.DisplayName = document.querySelector("#displayName").value;
            //userNow.Tag_CanTwitchSummon = document.querySelector("#tagCanTwitchSummon").checked;
            console.log(userNow);
            return userNow;
        }
        function getAccountsTree() {
        @{
            var sb = new StringBuilder();
            sb.Append("[{text: \"accounts\", \"expanded\":true, nodes: [");
            var first = true;
            foreach (var acc in Model.Accounts.OrderBy(a => a.SeenInChannel.LineageSummary))
            {
                if (!first)
                    sb.Append(',');
                sb.Append($"{{text: \"<div class=\\\"account {acc.Protocol}\\\"><div class=\\\"protocol-icon\\\">&nbsp;</div>{acc.SeenInChannel.LineageSummary}/<a href=\\\"/Accounts/Details/{acc.Id}\\\">{acc.DisplayName}</a>\"}}");
                first = false;
            }
            sb.Append("]}]");
        }
                console.log(@Html.Raw(sb.ToString()));
            var tree = @Html.Raw(sb.ToString());
            return tree;
        }

        $('#accountsTree').bstreeview({ data: getAccountsTree() });
        document.querySelectorAll("input[type=checkbox]").forEach(node => { node.onchange = () => { patchModel(jsonifyUser(), '/api/Users/') } });
    </script>
}
