{% 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 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 class="row w-100 m-0">
        <div class='col-12 col-md-10 offset-md-1 p-2'>
            <div class='row'>
                <div class='col-12 col-md-2 p-2'>
                    <div class='row'>
                        <div class='col-10 offest-1'>
                            <!-- START POSTER -->
                            <div class="new-stashr_poster-wrapper border rounded">
                                <div class="stashr-poster_container rounded">
                                    <img class="stashr-poster_background w-100" src="/static/assets/cover.svg" id="poster-bg">
                                    <a class="rounded stashr-poster_link">
                                        <img class="rounded stashr-poster_image w-100" id="lazy-img" v-bind:src="'/images/issues/'+collection.collection_cover_image+'.jpg'" onerror="this.src='/static/assets/cover.svg'">
                                    </a>
                                </div>
                            </div>
                            <!-- END POSTER -->
                        </div>
                    </div>
                </div>

                <div class="col-12 col-md-10 p-2">
                    <div class="row w-100 bg-light rounded m-0 p-4">
                        <div class="col-12 col-md-10">
                            <div class="row">
                                <div class="col text-center text-md-start">
                                    <h1 class="stashr-series_title">[[ collection.collection_name ]]</h1>
                                </div>
                            </div>
                            <div class="row text-center text-md-start">
                                <div class="col-12">
                                    <!-- START BADGES -->
                                    <span class="badge mx-1" :class="statusClass">[[ statusText ]]</span>
                                    <span class="badge bg-info mx-1">[[ collection.user.username ]]</span>
                                    {{ emit_tep('single_collection_page_badge_row', collection=collection) }}
                                    <!-- END BADGES -->
                                </div>
                            </div>
                            <div class="row">
                                <div class="col text-center text-md-start">
                                    <!-- START BUTTON -->
                                    <button class="btn btn-primary m-1" type="button" data-bs-toggle="modal" data-bs-target="#modalInfo" :data-collection_name="collection.collection_name" :data-collection_description="collection.collection_description">
                                        DESCRIPTION
                                    </button>
                                    {{ emit_tep('single_collection_page_button_row', collection=collection) }}
                                    <!-- END BUTTON -->
                                </div>
                            </div>
                        </div>
                        <div class="col-12 col-md-2 text-center text-md-right">
                            <!-- START ACTIONS -->
                            {% 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>
                                    {{ emit_tep('single_collection_page_action_dropdown', collection=collection) }}
                                </div>
                            </div>
                            {% endif %}
                            <!-- END ACTIONS -->
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>`,
    computed: {
        statusClass() {
            let classname = 'bg-danger';
            if (this.collection.collection_public) {
                classname = 'bg-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-cover_size m-2 js-sortable-block'
        @mouseover="hover = true"
        @mouseleave="hover = false"
    >
    <div class='stashr-poster_wrapper rounded'>
        {% if collection.collection_user_id == current_user.id %}
        <div class="stashr-badge_tl badge rounded-pill bg-dark border js-drag-handle">
            <i class="fas fa-arrows-alt"></i>
        </div>
        {% endif %}
        <div class="stashr-badge_br badge rounded-pill bg-dark border">
            <i class="fas fa-eye" :class="statusClass"></i>
        </div>
        <div class="stashr-poster_container border rounded">
            <div class="stashr-overlay_bottom w-100 center" v-if="hover">
                <a href="#">[[ issue.volume.volume_name ]] #[[ issue.issue_number ]]</a>
            </div>
            <img class="stashr-poster_background w-100" loading="eager" src="/static/assets/cover.svg" />
            <a class="stashr-poster_link" data-bs-toggle="modal" data-bs-target="#modalAction" @click="changeModal">
                <img class="w-100" loading="lazy" v-bind:src="'/images/issues/'+ issue.issue_id +'.jpg'"/>
            </a>
        </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 %}