<script>
    import {friendlyDate} from "../../helpers";
    import Avatar from "../account/Avatar.svelte";
    import {usernameById} from "../account/users";
    import {isEqual} from "lodash";
    import Status from "./Status.svelte";
    import Icon from "../common/Icon.svelte";
    import RevisionCell from "./revisions/RevisionCell.svelte";

    export let record;
    export let users;
    export let schema;
    let rollbackError = "";
    $: revisions = [];
    $: fieldsWithDiff = [];
    $: selectedRevision = null;
    $: recordEdges = {};
    $: selectedRevisionEdges = {};

    axios
        .get(`/records/${record.id}/revisions`)
        .then((response) => {
            revisions = response.data;
        })
        .catch((error) => {
            console.log(error);
        });

    function getEdgesByField(edges) {
        return schema.fields
            .filter((f) => ["file", "reference"].includes(f.ui))
            .reduce((c, f) => {
                let fieldEdges = edges
                    .filter((e) => e.field === f.name)
                    .map((e) =>
                        record._children.find((child) => child.id === e.to)
                    );

                c[f.name] = fieldEdges;
                return c;
            }, {});
    }

    function compare(e, revision) {
        e.preventDefault();
        selectedRevision = revision;

        fieldsWithDiff = schema.fields.filter((f) => {
            return !isEqual(selectedRevision.data[f.name], record.data[f.name]);
        });
    }

    function rollback(e) {
        e.preventDefault();
        rollbackError = "";
        axios
            .post(
                `/records/${record.id}/rollback/${selectedRevision._sys.version}`
            )
            .then((response) => {
                window.location.reload();
            })
            .catch((error) => {
                const firstError = error.response.data.error;
                rollbackError =
                    firstError.fieldLabel + ": " + firstError.message;
            });
    }
</script>

<div class="lx-card ">
    <div class="row">
        <div class="col-8">
            <div>
                <span class="label text-end text-muted">record id </span>
                <small>{record.id}</small>
            </div>
            <div>
                <span class="label text-end text-muted">current version </span>
                {record._sys.version}
            </div>
            <div>
                <span class="label text-end text-muted"> created </span>
                <Avatar
                    name={usernameById(users, record._sys.createdBy)}
                    side={24}
                />
                {friendlyDate(record._sys.createdAt)}
            </div>
            <div>
                <span class="label  text-end text-muted">updated </span>
                <Avatar
                    name={usernameById(users, record._sys.updatedBy)}
                    side={24}
                />
                {friendlyDate(record._sys.updatedAt)}
            </div>
        </div>
        <div class="col-4">
            <span class="label d-block text-muted "
            >Rules for this schema
            </span>
            <small>
                Revisions are retained for {schema.revisionRetentionDays} days
                <br/>
                Each record maintains the last {schema.revisionRetentionNumber}
                versions
            </small>
        </div>
    </div>
</div>
<div class="lx-card  mt-4">
    {#if schema.revisionRetentionDays > 0}
        <div class="header-small  mb-3">Revisions</div>
        {#each revisions as revision}
            {#if revision._sys.version != record._sys.version}
                <div
                    class="row  p-2 rounded"
                    class:active={revision._sys.version ===
                        selectedRevision?._sys.version}
                >
                    <div class="col-2">
                        <Status status={revision.status}/>
                    </div>
                    <div class="col-2">version {revision._sys.version}</div>
                    <div class="col-5">
                        <Avatar
                            name={usernameById(users, revision._sys.updatedBy)}
                            side={24}
                        />
                        {friendlyDate(revision._sys.updatedAt)}
                    </div>

                    <div class="col-3 text-center">
                        <button
                            disabled={revision._sys.version ===
                                selectedRevision?._sys.version}
                            class="btn btn-sm btn-outline-primary"
                            on:click={(e) => compare(e, revision)}
                        >Compare
                        </button
                        >
                    </div>
                </div>
            {/if}
        {/each}
    {:else}
        <div class="card-body">
            <span>Revisions are not enabled for this Schema</span>
        </div>
    {/if}
</div>
{#if selectedRevision}
    <div class="mt-4">
        {#if fieldsWithDiff.length > 0}
            <p class="text-center fw-bold mb-3 mt-5">
                If you choose to rollback to this revision
            </p>
            <button
                on:click={rollback}
                class="btn  btn-primary mb-5 d-block mx-auto"
            >
                Rollback to version {selectedRevision._sys.version}
            </button>

            {#if rollbackError}
                <span class="d-block text-danger mt-3">{rollbackError}</span>
            {/if}
            <div class="mt-3">
                {#each fieldsWithDiff as field}
                    <!-- <div
                        class=" lx-card d-flex p-4 mb-4"
                        style="overflow:hidden"
                    > -->
                    <!-- <div class="d-block" style="width:200px;">
                            {field.label}
                        </div> -->
                    <div
                        class="lx-card row p-4 mb-4 w-100"
                        style="overflow:hidden"
                    >
                        <div class="col-5">
                            <RevisionCell
                                edges={recordEdges}
                                {field}
                                side={record.data[field.name]}
                                colorClass="text-danger"
                            />
                        </div>
                        <div class="col-2">
                            <div
                                class="h-100 d-flex align-items-center justify-content-center text-secondary"
                            >
                                <span class="me-1">{field.label}</span>
                                <Icon
                                    icon="angle-right"
                                    width="12"
                                    height="12"
                                />
                            </div>
                        </div>
                        <div class="col-5">
                            <RevisionCell
                                edges={selectedRevisionEdges}
                                {field}
                                side={selectedRevision.data[field.name]}
                                colorClass="text-success"
                            />
                        </div>
                    </div>
                    <!-- </div> -->
                {/each}
            </div>
        {:else}
            <div class=" lx-card text-center">
                <span>Nothing will change</span>
            </div>
        {/if}
    </div>
{/if}

<style>
    .label {
        width: 180px;
        margin-right: 10px;
        margin-bottom: 4px;
        display: inline-block;
    }


    .active {
        background-color: #eee;
        border: 1px solid #ccc;
    }
</style>
