{% extends "base.html" %}

{% block header_script_files %}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sortablejs@1.8.4/Sortable.min.js"></script>
{% endblock %}

{% block header %}
{{ emit_tep('single_collection_page_header', collection=collection) }}
{% endblock %}

{% block content %}

<div id="app">
    <collection-jumbo ref="jumbo" v-bind:collection='collection'></collection-jumbo>
    <issues ref="issues" v-bind:issues='issues'></issues>
    <collection-modals v-bind:collection='collection'></collection-modals>
    <issue-modals v-bind:issue='issue' v-bind:owner='collection.user.id'></issue-modals>
</div>

{% endblock %}

{% block modals %}
{{ emit_tep('single_collection_page_modals', collection=collection) }}
{% endblock %}

{% block button_container %}
{{ emit_tep('single_collection_page_button_container', collection=collection) }}
{% endblock %}

{% block script %}

Vue.directive('sortable', {
    inserted (el, binding, vnode) {
        let options = binding.value;
        options.onUpdate = (e) => vnode.data.on.sorted(e);
        const sortable = Sortable.create(el, binding.value);
    }
})

Vue.component('issue-modals', {
    props: ['issue', 'owner'],
    template: `
    <div>
        <div class="modal" id="modalAction" tabindex="-1" role="dialog" aria-labelledby="actionModal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">
                            [[ issue.volume.volume_name || 'something' ]] #[[ issue.issue_number || 'something' ]]
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body text-center">
                        <a :href="'/read/'+issue.issue_id" id="actionRead" class="btn btn-success my-1">
                            <i class="fas fa-book-open"></i>
                            Read
                        </a>
                        {% if (current_user.role.lower() == 'admin') or
                              (current_user.role.lower() == 'librarian') or
                              (current_user.role.lower() == 'patron') %}
                        <a :href="'/api/downloads/'+issue.issu_id" id="actionDownload" class="btn btn-success my-1">
                            <i class="fas fa-download"></i>
                            Download
                        </a>
                        {% endif %}
                        <hr>
                        <button @click="toggleRead" id="actionToggle" class="btn btn-info my-1" data-bs-dismiss="modal">
                            <i class="fas fa-check"></i>
                            Toggle Read
                        </button>
                        <span v-if="{{ current_user.id }} == owner" >
                            <button @click="removeFromCollection" id="actionRemove" class="btn btn-danger my-1" data-bs-dismiss="modal">
                                <i class="fas fa-minus"></i>
                                Remove From Collection
                            </button>
                            <hr>
                            <button @click="setCover" id="actionCover" class="btn btn-danger my-1" data-bs-dismiss="modal">
                                <i class="fas fa-portrait"></i>
                                Set as Collection Cover
                            </button>
                        </span>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        {{ emit_tep('single_collection_page_issue_modals', collection=collection) }}
    </div>`,
    methods: {
        toggleRead() {
            app.$refs.issues.$children.find(child => { return child.$vnode.key == this.issue.issue_id }).toggleRead()
        },
        removeFromCollection() {
            app.$refs.issues.$children.find(child => { return child.$vnode.key == this.issue.issue_id }).removeFromCollection()
        },
        setCover() {
            app.$refs.issues.$children.find(child => { return child.$vnode.key == this.issue.issue_id }).setCover()
        },
    },
    data() { return { curuser: {{ current_user.id }} } },
    delimiters: ["[[","]]"]
})

Vue.component('collection-modals', {
    props: ['collection'],
    template: `
    <div>
        <div class="modal" id="modalInfo" tabindex="-1" role="dialog" aria-labelledby="infoModal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">
                            [[ this.collection.collection_name ]]
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        [[ this.collection.collection_description ]]
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        
        {% if collection.collection_user_id == current_user.id %}
        
        <div class="modal" id="modalEditCollection" tabindex="-1" role="dialog" aria-labelledby="editCollectionModal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content"> 
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">
                            <span id="collectionName">Edit Collection</span>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                        <div class="form-group">
                            <label for="collection_name">Collection Name:</label>
                            <input id="collection_name" class="form-control" type="text" placeholder="Default input" :value="this.collection.collection_name">
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="collection_public" :checked='this.collection.collection_public'>
                            <label class="form-check-label" for="collection_public">
                                Make Collection Public
                            </label>
                        </div>
                        <div class="form-group">
                            <label for="comment">Description:</label>
                            <textarea class="form-control" rows="3" id="collection_description" :value="this.collection.collection_description"></textarea>
                        </div>
                    </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-success" data-bs-dismiss="modal" @click="editCollection">Update</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal" id="modalDeleteCollection" tabindex="-1" role="dialog" aria-labelledby="deleteCollectionModal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">
                            <span id="collectionName">Delete Collection</span>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        Are you sure you want to delete this collection?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal" @click="removeCollection">Delete</button>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
        {{ emit_tep('single_collection_page_collection_modals', collection=collection) }}
    </div>
    `,
    methods: {
        removeCollection() {
            app.removeCollection()
        },
        editCollection() {
            app.editCollection()
        },
    },
    delimiters: ["[[","]]"]
})

Vue.component('collection-jumbo', {
    props: ['collection'],
    template: `
    <div>
        <div class="d-grid w-100 bg-mine m-0 p-0 sticky-top shadow">
            <div class="row d-flex flex-nowrap w-100 m-0 p-3 bg-mine">
                <div class="flex-shrink-1">
                    <div class="row w-100 m-0 p-0">
                        <div class="col-12 col-md-10 text-start">
                            <span role="button" data-bs-toggle="modal" data-bs-target="#modalInfo">
                                <span class="fs-1 text-white stashr-series_title">[[ collection.collection_name ]]</span>
                                <i class="fas fa-info-circle text-secondary"></i>
                            </span>
                            <h5>
                                <span class="badge bg-dark">
                                    <i class="fas fa-circle" v-bind:class="statusClass"></i>
                                    [[ statusText ]]
                                </span>
                                <span class="badge bg-dark">
                                    <i class="fas fa-user"></i>
                                    [[ collection.user.username ]]
                                </span>
                            </h5>
                        </div>
                    </div>
                </div>
                <a class="fa-stack p-0 text-white">
                    <i class="fas fa-bars fa-stack-1x" data-bs-toggle="offcanvas" href="#offcanvasRight" role="button"></i>
                </a>
            </div>
        </div>
        <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
            <div class="offcanvas-header">
                <h5 id="offcanvasRightLabel">[[ collection.collection_name ]]</h5>
                <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">
                <button type="button" class="btn btn-info w-100 m-1" data-bs-toggle="modal" data-bs-target="#modalEditCollection">
                    <i class="fas fa-edit mx-1"></i>
                    Edit Collection
                </button>
                <button type="button" class="btn btn-info w-100 m-1" data-bs-toggle="modal" data-bs-target="#modalDeleteCollection">
                    <i class="fas fa-trash-alt mx-1"></i>
                    Delete Collection
                </button>
            </div>
        </div>
    </div>
    <!--
    <div class="d-grid w-100 bg-mine m-0 p-0 sticky-md-top shadow">
        <div class="row w-100 m-0 p-3">
            <div class="col-12 col-md-10 text-center text-md-start">
                <span class="fs-1 text-white stashr-series_title">[[ collection.collection_name ]]</span>
                <span role="button" data-bs-toggle="modal" data-bs-target="#modalInfo">
                    <i class="fas fa-info-circle text-secondary"></i>
                </span>
                <h5>
                    <span class="badge bg-dark">
                        <i class="fas fa-circle" v-bind:class="statusClass"></i>
                        [[ statusText ]]
                    </span>
                    <span class="badge bg-dark">
                        <i class="fas fa-user"></i>
                        [[ collection.user.username ]]
                    </span>
                </h5>
            </div>
            <div class="col-12 col-md-2 text-center text-md-end">
                {% if collection.collection_user_id == current_user.id %}
                <div class="dropdown">
                    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Actions
                    </button>
                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
                        <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#modalEditCollection">
                            <i class="fas fa-edit"></i>
                            Edit Collection
                        </a>
                        <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#modalDeleteCollection">
                            <i class="fas fa-trash-alt"></i>
                            Delete Collection
                        </a>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    -->
    `,
    computed: {
        statusClass() {
            let classname = 'text-danger';
            if (this.collection.collection_public) {
                classname = 'text-success';
            };
            return classname;
        },
        statusText() {
            let text = 'Private';
            if (this.collection.collection_public) {
                text = 'Public';
            }
            return text;
        }
    },
    delimiters: ["[[","]]"]
})

Vue.component('issues', {
    props: ['issues'],
    template: `
    <div>
        <ul class="d-flex flex-wrap w-100 m-0 p-0 justify-content-center" v-sortable="$options.sortOptions" @sorted='handleSorted'>
            <issue
                v-for="issue in issues"
                v-bind:issue="issue"
                v-bind:key="issue.issue_id"
            ></issue>
        </ul>
    </div>`,
    methods: {
        handleSorted(event) {
            app.handleSorted(event)
        },
    },
    sortOptions: {
        draggable: '.js-sortable-block',
        handle: '.js-drag-handle',
        delay: 300,
        delayOnTouchOnly: true
    },
    delimiters: ["[[","]]"],
})

Vue.component('issue', {
    props: ['issue'],
    template: `
    <li class='stashr-item_container m-2 js-sortable-block'
        @mouseover="hover = true"
        @mouseleave="hover = false"
    >
        <div class="stashr-poster_container border border-dark rounded-3">
            {% if collection.collection_user_id == current_user.id %}
            <div class="stashr-badge_top_left bg-dark js-drag-handle">
                <span class="fa-stack p-0">
                    <i class="fas fa-arrows-alt fa-stack-1x text-white"></i>
                </span>
            </div>
            {% endif %}
            <div class="stashr-badge_bottom_right bg-dark">
                <span class="fa-stack p-0">
                    <i class="fas fa-eye fa-stack-1x" :class="statusClass"></i>
                    <i class="fas fa-slash fa-stack-1x text-danger" v-if="!this.issue.read_status[0].read_status"></i>
                </span>
            </div>
            <div data-bs-toggle="modal" data-bs-target="#modalAction" @click="changeModal">
                <img class="stashr-background w-100" loading="eager" src="/static/assets/cover.svg" />
                <img class="stashr-poster w-100" loading="lazy" v-bind:src="'/images/issues/'+ issue.issue_id +'.jpg'" />
            </div>
            <div class="stashr-overlay_bottom w-100 text-center shadow" v-if="hover" data-bs-toggle="modal" data-bs-target="#modalAction" @click="changeModal">
                [[ issue.volume.volume_name ]] #[[ issue.issue_number ]]
            </div>
        </div>
    </li>
    `,
    computed: {
        statusClass() {
            let classname = 'text-danger';
            if (this.issue.read_status[0].read_status) {
                classname = 'text-success';
            }
            return classname;
        },
    },
    methods: {
        setCover() {
            app.setCover()
        },
        toggleRead() {
            axios.put('{{ url_for('api.api_put_single_issue', issue_id='ISSUEID') }}'.replace('ISSUEID', this.issue.issue_id), {
                data: {
                    read_status: !this.issue.read_status[0].read_status
                }
            })
                .then(res => {
                    if(res.data.status_code == '200') {
                        stashrToast('Toggled Read Status', 'success');
                        this.issue.read_status[0].read_status = !this.issue.read_status[0].read_status
                    } else {
                        stashrToast(res.data.message, 'error')
                    }
                })
                .catch(err => console.log(err))
        },
        removeFromCollection() {
            app.removeFromCollection()
        },
        changeModal() {
            app.changeModal(this.issue)
        }
    },
    data() { return { hover: false } },
    delimiters: ["[[","]]"],
})

var app = new Vue({
    el: '#app',
    data: {
        collection: [],
        issues: [],
        issue: [],
    },
    created() {
        this.getCollection()
        this.getIssues()
    },
    methods: {

        getCollection() {
            console.log('gettingcollection')
            console.log('{{ url_for('api.api_get_single_collection', collection_slug=collection_slug) }}')
            axios.get('{{ url_for('api.api_get_single_collection', collection_slug=collection_slug) }}')
                .then(res => {
                    this.collection = res.data.results
                })
                .catch(err => console.log(err))
        },

        getIssues() {
            axios.get('{{ url_for('api.api_get_collection_all_issues', collection_slug=collection_slug) }}', {
                params: {
                    offset: this.issues.length
                }
            })
                .then(res => {
                    if(res.data.number_of_page_results > 0) {
                        res.data.results.forEach(result => {
                            this.issues.push(result)
                        })
                        if(this.issues.length < res.data.number_of_total_results) {
                            this.getIssues()
                        }
                    }
                    this.issue = this.issues[0]
                })
            
        },

        changeModal(issue) {
            this.issue = issue
        },

        editCollection() {
            new_name = document.getElementById('collection_name').value;
            new_public = document.getElementById('collection_public').checked;
            new_description = document.getElementById('collection_description').value;
            axios.put('{{ url_for('api.api_put_single_collection', collection_slug=collection_slug) }}', {
                data: {
                    collection_name: new_name,
                    collection_public: new_public,
                    collection_description: new_description,
                }
            })
                .then(res => {
                    if(res.data.status_code=='200'){
                        stashrToast('Updated Collection', 'success')
                        this.collection.collection_name = new_name;
                        this.collection.collection_description = new_description;
                        this.collection.collection_public = new_public;
                    }else{
                        stashrToast(res.data.message, 'error')
                    }
                })
                .catch(err => console.log(err))
        },

        setCover() {
            axios.put('{{ url_for('api.api_put_single_collection', collection_slug='COLLECTIONID') }}'.replace('COLLECTIONID', this.collection.collection_id), {
                data: {
                    collection_cover_image: this.issue.issue_id
                }
            })
                .then(res => {
                    if(res.data.status_code == '200') {
                        stashrToast('Cover Image Set', 'success');
                        app.$refs.jumbo.collection.collection_cover_image = this.issue.issue_id;
                    } else {
                        stashrToast(res.data.message, 'error')
                    }
                })
                .catch(err => console.log(err))
        },

        handleSorted(event) {
            axios.put('{{ url_for('api.api_put_single_collection', collection_slug='COLLECTIONID') }}'.replace('COLLECTIONID', this.collection.collection_id), {
                data: {
                    old_index: event.oldIndex,
                    new_index: event.newIndex
                }
            })
                .then(res => {
                    if(res.data.status_code== '200') {
                        stashrToast('Updated Order', 'success')
                    } else {
                        stashrToast(res.data.message, 'error')
                    }
                })
                .catch(err => console.log(err))
        },

        removeFromCollection() {
            axios.delete('{{ url_for('api.api_delete_collection_issue', collection_slug=collection_slug, issue_id='ISSUEID') }}'.replace('ISSUEID', this.issue.issue_id))
                .then(res => {
                    if(res.data.status_code == '200') {
                        stashrToast('Removed from Collection', 'success')
                    } else {
                        stashrToast(res.data.message, 'error')
                    }
                })
                .catch(err => console.log(err))
            this.issues = this.issues.filter(issue => issue.issue_id !== this.issue.issue_id)
            // this.issues = this.issues.filter(remove => this.remove.issue_id !== app.issue.issue_id)
        },

        removeCollection() {
            console.log('removing collection')
            axios.delete('{{ url_for('api.api_delete_single_collection', collection_slug=collection_slug) }}')
                .then(res =>{
                    window.location.replace('{{ url_for('all_collections_page') }}')
                })
                .catch(err => console.log(err))
        },
        
    },
    delimiters: ["[[","]]"]
})

{{ emit_tep('single_collection_page_script', collection=collection) }}

{% endblock %}