{% extends 'abase.axml' %}
{% from 'actions.axml' import pagination %}

{% macro commander() %}
{
    isFilterable: false,
    oldPagination: pagination,
    idSearch: '',
    eventSearch: '',
    producerSearch: '',
    endpointSearch: '',
    descriptionSearch: '',
    whenFilter: '',
    filterResults(){
        let base = `/v1/subscribers?pagination=${100}&page=${page}`;
        if(this.idSearch) base = `${base}&id=${this.idSearch}`;
        if(this.eventSearch) base = `${base}&event=${this.eventSearch}`;
        if(this.producerSearch) base = `${base}&producer=${this.producerSearch}`;
        if(this.endpointSearch) base = `${base}&endpoint=${this.endpointSearch}`;
        if(this.descriptionSearch) base = `${base}&description=${this.descriptionSearch}`;
        if(this.whenFilter) base = `${base}&timeline=${this.whenFilter}`;
        fetch(`${base}`)
            .then(response => response.json())
            .then(data => {
                isFiltering = true;
                subscribers = data;
            })
            .catch(err => {
                ShowFeedback('error', 'Filter operation failed...')
            })
        },
        clearFilter(){
            this.idSearch = '';
            this.eventSearch = '';
            this.producerSearch = '';
            this.endpointSearch = '';
            this.descriptionSearch = '';
            this.whenFilter = '';
            isFiltering = false;
            fetchAll();
        },
        checkDirty(){
            if(
                this.idSearch !== '' || this.eventSearch !== '' ||
                this.producerSearch !== '' || this.endpointSearch !== '' ||
                this.descriptionSearch !== '' || this.whenFilter !== ''
            ) {
                this.isFilterable = true;
                return true;
            }
            this.isFilterable = false;
            return false;
        }
    }
{% endmacro %}

{% block easel %}
<section x-data="{{ controller('subscriptions') }}">
    <div><span class="px-3 font-800">Filters:</span></div>
    <div class="px-3 pb-2" x-data="{{ commander() }}" x-effect="checkDirty">
        <span class="display-inline-block">
            <input
                type="text"
                placeholder="s. id"
                x-model="idSearch"
                style="width: 5em"
            />
            <input
                type="text"
                placeholder="producer name..."
                style="width: 13em"
                x-model="producerSearch"
            />
            <input
                type="text"
                placeholder="event name..."
                style="width: 15em"
                x-model="eventSearch"
            />
            <input
                style="width: 14em"
                type="text"
                placeholder="susbscription endpoint..."
                x-model="endpointSearch"
            />
            <input
                type="text"
                placeholder="subscription description..."
                style="width: 18em"
                x-model="descriptionSearch"
            />
            <select x-model="whenFilter">
                <option>Select Day</option>
                <template
                    x-for="[val, txt] in Object.entries({today: 'Today', week: 'This Week', month: 'This Month'})"
                    :key="val"
                >
                    <option :value="val" x-text="txt"></option>
                </template>
            </select>
            <button @click="filterResults" :disabled="! isFilterable">
                <ion-icon name="search" class="font-size-xs"></ion-icon>
                search
            </button>
            <button disabled>&nbsp;</button>
            <button @click.self="clearFilter" :disabled="! isFiltering">
                clear filter
                <ion-icon name="leaf-outline" class="font-size-xs"></ion-icon>
            </button>
        </span>
    </div>

    <div class="easel" x-init="calculateHeight($el, 10); fetchAll()">
        <table class="table is-striped is-fullwidth is-hoverable paginated">
            <thead>
                <th style="width: 5%">SID</th>
                <th>Application</th>
                <th>Action</th>
                <th>Endpoint</th>
                <th>Max Retries</th>
                <th>Timestamped</th>
            </thead>
            <tbody x-init="() => { calculateHeight($el, 100); }">
                <template x-for="sub in subscriptions">
                    <tr>
                        <td x-text="sub.subscription" style="width: 5%"></td>
                        <td x-text="sub.application"></td>
                        <td x-text="sub.action"></td>
                        <td>
                            <code
                                x-text="sub.endpoint"
                                class="font-size-sm"
                            ></code>
                        </td>
                        <td x-text="sub.max_retries"></td>
                        <td x-text="sub.timestamped"></td>
                    </tr>
                </template>
            </tbody>
            <tfoot style="position: sticky; bottom: 0">
                <th>Subscription</th>
                <th>Application</th>
                <th>Action</th>
                <th>Endpoint</th>
                <th>Description</th>
                <th>Timestamped</th>
            </tfoot>
        </table>
        {{ pagination() }}
    </div>
</section>
{% endblock %}


{% block wizard %}
<span x-data="{
    ide: null,
    applications: [],
    actions: [],
    application: 'alphatesting',
    secret: 'sometime-sometime',
    action: '',
    handler: '/v1/change-me',
    description: '',
    max_retries: 3,
    actionContainer: '',
    fetchApplications(){
        fetch('/v1/applications', {
            method: 'GET'
        }).then(res => {
            if(res.status !== 200) throw Error();
            return res.json()
        }).then(data => {
            this.applications = data;
        }).catch(err => {
        })
    },
    fetchActions(){
        fetch(`/v1/actions?application=${this.actionContainer}`, {
            method: 'GET'
        }).then(res => {
            if(res.status !== 200) throw Error();
            return res.json()
        }).then(data => {
            this.actions = data;
        }).catch(err => {
        })
    },
    resetForm(){
        this.handler = '';
        this.description = '';
        this.application = '';
        this.action = '';
        this.subscriber = null;
        this.max_tries = 3;
    },
    saveSubscription(){
        superpost('/v1/subscriptions').send({
            application: this.application,
            secret: this.secret,
            action: this.action,
            max_retries: this.max_retries,
            handler: this.handler
        }).then(res => {
            supertoast('info', 'Event published successfully')
            this.resetForm();
            $dispatch('refresher');
            showModalContent = false;
        }).catch(err => {
            supertoast('error', err.response.body.error);
        })
    },
    get Activated(){
        if(!this.application.length) return '';
        const activated = this.applications.find(app => app.application === this.application);
        return activated ? activated.address.slice(0, -1) : '';
    }
}">
    <div class="modal-card-body p-5">
        <div class="brick vertical-aligns-middle">
            <label class="font-800 mr-2 vertical-aligns-middle">Subscriber Application: </label>
            <div class="select">
                <select x-model="application" x-init="fetchApplications">
                    <option value="">Select subscribing Application</option>
                    <template x-for="a in applications">
                        <option x-text="a.application" @click="activated = a"></option>
                    </template>
                </select>
            </div>
        </div>
        <div class="brick vertical-aligns-middle">
            <label class="font-800 mr-2">secret: </label>
            <div class="control display-inline-block has-icons-right" x-data="{
                visible: false
            }">
                <input :type="visible ? 'text' : 'password'" class="w-30em input" placeholder="Enter secret for application..." x-model="secret">
                <span class="icon is-right" @click="visible = !visible">
                    <img :src="`/public/icons/${visible ? 'eye' : 'neye'}.svg`" class="pointer-events-all"></img>
                </span>
            </div>
        </div>
        <div class="brick vertical-aligns-middle">
            <label class="font-800 mr-2">Publisher/Action: </label>
            <div class="select">
                <select x-model="actionContainer">
                    <option value="">Select action Application</option>
                    <template x-for="app in applications">
                        <option :value="app.application" x-text="app.application"></option>
                    </template>
                </select>
            </div>
            <template x-if="actionContainer.length">
                <div class="select" x-effect="() => {
                        if(actionContainer.length) fetchActions();
                    }">
                    <select x-model="action">
                        <option value="">Select An Action</option>
                        <template x-for="dat in actions">
                            <option :value="dat.action" x-text="`(${dat.id}): ${dat.action}`"></option>
                        </template>
                    </select>
                </div>
            </template>
        </div>
        <div class="brick vertical-aligns-middle">
            <label class="font-800 mr-2 vertical-aligns-middle">Max Retries: </label>
            <input type="number" class="w-5em input" placeholder="Retry max times..." x-model="max_retries">
        </div>
        <div class="brick vertical-aligns-middle">
            <label class="font-800 mr-2 vertical-aligns-middle">Handler URL: </label>
            <div class="display-flex align-items-center">
                <p class="has-text-weight-bold" x-text="Activated || 'http://address:80'" :class="Activated.length ? 'has-text-info' : 'has-text-danger'"></p>
                <span>&nbsp;</span>
                <input type="text" class="w-30em input" placeholder="/Application Callback URL..." x-model="handler">
            </div>
        </div>
    </div>
    <div class="modal-card-foot">
        <button class="button primary" @click="saveSubscription">Save Subscription</button>
    </div>
</span>
{% endblock %}
