<div class="ui inverted grey two column grid segment">
    <div class="column">
        COMENTARIOS
    </div>
    <div class="right aligned column">
        <a href="javascript: addComment()" style="color: inherit;">
            <i class="plus icon"></i>
        </a>
    </div>
</div>
<div class="ui segment">
    <table class="ui very basic table">
        <tbody id="comentarios"></tbody>
    </table>
</div>

@push('page_scripts')
    <script type="text/javascript">
        class Comentario
        {
            fecha
            texto

            constructor({fecha, texto})
            {
                this.fecha = new Date(fecha + 'T00:00:00')
                this.texto = texto
            }
            draw(dateFormatter)
            {
                return $('<tr></tr>').append(
                    $('<td></td>').html(dateFormatter.format(this.fecha))
                ).append(
                    $('<td></td>').html(this.texto)
                ).append(
                    $('<td></td>').addClass('right aligned').append(
                        $('<a></a>').attr('href', 'javascript: removeComment();').append(
                            $('<i></i>').addClass('minus icon')
                        )
                    )
                )
            }
        }
        const comentarios = {
            comentarios: [],
            id: '',
            fetch: function() {
                return {
                    comentarios: () => {
                        const uri = '{{$urls->api}}/venta/{{$venta->id}}/comentarios'
                        return fetch(uri).then(response => {
                            if (response.ok) {
                                return response.json()
                            }
                        }).then(data => {
                            if (data.total === 0) {
                                return
                            }
                            data.comentarios.forEach(settings => {
                                this.comentarios.push(new Comentario(settings))
                            })
                            this.draw().comentarios()
                        })
                    }
                }
            },
            draw: function() {
                return {
                    comentarios: () => {
                        const body = $(this.id)
                        const dateFormatter = new Intl.DateTimeFormat('es-CL', {dateStyle: 'medium'})
                        body.html('')
                        this.comentarios.forEach(comentario => {
                            body.append(comentario.draw(dateFormatter))
                        })
                    }
                }
            },
            setup: function(id) {
                this.id = id
                this.fetch().comentarios()
            }
        }
        $(document).ready(() => {
            comentarios.setup('#comentarios')
        })
    </script>
@endpush
