<script type="text/x-template" id="mediaitem-square-sp">
    <div ref="main" style="position: relative; display: inline-flex;" @contextmenu="contextMenu"  v-observe-visibility="{callback: visibilityChanged}" width="250px">
        <div @click.self='app.routeView(item)' v-if="isVisible"
             class="cd-mediaitem-square-sp" ref="main2"
             :style="{'--spcolor' : (item.attributes.artwork.bgColor != null) ? ('#'+item.attributes.artwork.bgColor) : `black`}">
            <div class="artwork">
                <mediaitem-artwork
                        :url="item.attributes.artwork ? item.attributes.artwork.url : ''"
                        size="300"
                        :video="(item.attributes != null && item.attributes.editorialVideo != null) ? (item.attributes.editorialVideo.motionDetailSquare ? item.attributes.editorialVideo.motionDetailSquare.video : (item.attributes.editorialVideo.motionSquareVideo1x1 ? item.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' "
                        :type="item.type"></mediaitem-artwork>
            </div>
            <div class="cd-mediaitem-square-large-overlay" @click.self='app.routeView(item)'>
                <div class="button" style="
                    border-radius: 50%;
                    background: rgba(50,50,50,0.7);"
                     :style="[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'margin': '153px','position': 'absolute','margin-left': '153px',
                        width: '30px',
                        height: '30px',} :
                        {margin: '35px',display:'none',
                        width: '120px',
                        height: '120px',}]" @click="clickContext()">
                    <%- include("../svg/more.svg") %>
                </div>
                <div class="button" style="
                    border-radius: 50%;
                    background: rgba(50,50,50,0.7);"
                     :style="[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'position': 'absolute','margin': '153px',
                        width: '30px', 'margin-left': '8px',
                        height: '30px',} :
                        {margin: '35px','position': 'absolute',
                        width: '120px',
                        height: '120px',}]" @click="app.playMediaItem(item)">
                    <%- include("../svg/play.svg") %>
                </div>
            </div>
            <div class="title text-overflow-elipsis"
                 :style="{'color' : (item.attributes.artwork.textColor1 != null) ? ('#'+item.attributes.artwork.textColor1) : `#eee`}"
                 style="font-weight: 600">
                {{ item.attributes.name }}
            </div>
            <div class="subtitle text-overflow-elipsis "
                 :class="{'item-navigate': ((item.attributes.editorialNotes == null) && item.attributes.artistName)}"
                 :style="{ 'z-index': ((item.attributes.editorialNotes == null) && item.attributes.artistName) ? '4' : '' ,'color' : (item.attributes.artwork.textColor1 != null) ? ('#'+item.attributes.artwork.textColor1) : `#eee`}"
                 style="padding-left: 4px;padding-right: 4px; display: -webkit-box;-webkit-box-orient: vertical; -webkit-line-clamp: 2;white-space: normal;"
                 @click="subtitleSearchNavigate(item)"
            >
                {{ (item.attributes.editorialNotes != null) ? item.attributes.editorialNotes.short
                :(item.attributes.artistName ?? '') }}
            </div>

        </div>
        <div class="cd-mediaitem-square-large-overlay" @click.self='app.routeView(item)' tabindex="0" v-if="isVisible">
            <div class="button" style="
               border-radius: 50%;
               background: rgba(50,50,50,0.7);"
                 :style="[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'margin': '153px','position': 'absolute','margin-left': '153px',
                   width: '30px',
                   height: '30px',} :
                   {margin: '35px','position': 'absolute', display: 'none',
                   width: '120px',
                   height: '120px',}]" @click="clickContext()">
                <%- include("../svg/more.svg") %>
            </div>
            <div class="button" style="
                border-radius: 50%;
                background: rgba(50,50,50,0.7);"
                 :style="[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'position': 'absolute','margin': '153px',
                    width: '30px', 'margin-left': '8px',
                    height: '30px',} :
                    {margin: '35px','position': 'absolute',
                    width: '120px',
                    height: '120px',}]" @click="app.playMediaItem(item)">
                <%- include("../svg/play.svg") %>
            </div>
        </div>
    </div>
</script>

<script>
    Vue.component('mediaitem-square-sp', {
        template: '#mediaitem-square-sp',
        props: ['item'],
        data: function () {
            return {
                app: this.$root,
                isVisible: true,
                addedToLibrary : false,
            }
        },
        methods: {
            revisedRandId() {
                return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
            },
            async isInLibrary() {
                if (this.item.type && !this.item.type.includes("library")) {
                    var params = {"fields[playlists]": "inLibrary", "fields[albums]": "inLibrary", "relate": "library", "extend": this.revisedRandId()}
                    var res = await app.mkapi(this.item.attributes.playParams.kind ?? this.item.type, this.item.attributes.playParams.isLibrary ?? false, this.item.attributes.playParams.id ?? this.item.id, params);
                    res = res.data.data[0]
                    this.addedToLibrary = (res && res.attributes && res.attributes.inLibrary) ? res.attributes.inLibrary : false
                } else {
                    this.addedToLibrary = true
                }
            },
            async removeFromLibrary(id) {
                var params = {"fields[playlists]": "inLibrary","fields[songs]": "inLibrary", "fields[albums]": "inLibrary", "relate": "library", "extend": this.revisedRandId()}
                var id = this.item.id ?? this.item.attributes.playParams.id
                var res = await app.mkapi(this.item.attributes.playParams.kind ?? this.item.type, this.item.attributes.playParams.isLibrary ?? false, this.item.attributes.playParams.id ?? this.item.id, params);
                res = res.data.data[0]
                if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {
                    id = res.relationships.library.data[0].id
                }
                let kind = this.item.attributes.playParams.kind ?? this.item.type ?? '';
                var truekind = (!kind.endsWith("s")) ? (kind + "s") : kind;
                app.mk.api.v3.music(`v1/me/library/${truekind}/${id.toString()}`,{},
                    {
                    fetchOptions: {
                    method: "DELETE"
                }})
                this.addedToLibrary = true
            },
            subtitleSearchNavigate(item) {
                if((item.attributes.editorialNotes == null) && item.attributes.artistName)app.searchAndNavigate(item,'artist')
            },
            clickContext() {
                var evt = document.createEvent('MouseEvent');
                var rect = this.$refs.main2.getBoundingClientRect();
                evt.initMouseEvent(
                    "contextmenu",
                    true /* bubble */, true /* cancelable */,
                    window, null,
                    0, 0, rect.x + 100, rect.y + 100,  /* coordinates */
                    false, false, false, false, /* modifier keys */
                    0 /*left*/, null
                );
                this.$refs.main.dispatchEvent(evt);
            }
            ,
            visibilityChanged: function (isVisible, entry) {
                this.isVisible = isVisible
            },
            async contextMenu(event)  {
                if (!event) {
                    event = this.$refs.main
                } else {
                    console.log(event)
                }
                let self = this
                let useMenu = "normal"
                await this.isInLibrary()
                if (app.selectedMediaItems.length <= 1) {
                    app.selectedMediaItems = []
                    app.select_selectMediaItem(this.item.attributes.playParams.id ?? this.item.id, this.item.attributes.playParams.kind ?? this.item.type, this.index, this.guid, this.item.attributes.playParams.isLibrary ?? false)
                } else {
                    useMenu = "multiple"
                }
                let menus = {
                    multiple: {
                        items: [
                            {
                                name: `Play ${app.selectedMediaItems.length} tracks next`,
                                action: () => {
                                    let itemsToPlay = {}
                                    app.selectedMediaItems.forEach(item => {
                                        if (!itemsToPlay[item.kind]) {
                                            itemsToPlay[item.kind] = []
                                        }
                                        itemsToPlay[item.kind].push(item.id)
                                    })
                                    // loop through itemsToPlay
                                    for (let kind in itemsToPlay) {
                                        let ids = itemsToPlay[kind]
                                        if (ids.length > 0) {
                                            app.mk.playNext({[kind + "s"]: itemsToPlay[kind]})
                                        }
                                    }
                                    console.log(itemsToPlay)
                                    app.selectedMediaItems = []
                                }
                            },
                            {
                                name: `Play ${app.selectedMediaItems.length} tracks later`,
                                action: () => {
                                    let itemsToPlay = {}
                                    app.selectedMediaItems.forEach(item => {
                                        if (!itemsToPlay[item.kind]) {
                                            itemsToPlay[item.kind] = []
                                        }
                                        itemsToPlay[item.kind].push(item.id)
                                    })
                                    // loop through itemsToPlay
                                    for (let kind in itemsToPlay) {
                                        let ids = itemsToPlay[kind]
                                        if (ids.length > 0) {
                                            app.mk.playLater({[kind + "s"]: itemsToPlay[kind]})
                                        }
                                    }
                                    app.selectedMediaItems = []
                                }
                            },
                        ]
                    },
                    normal: {
                        items: [

                            {
                                "name": "Play Next",
                                "action": function () {
                                    app.mk.playNext({[self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id})
                                    app.mk.queue._reindex()
                                    app.selectedMediaItems = []
                                }
                            },
                            {
                                "name": "Play Later",
                                "action": function () {
                                    app.mk.playLater({[self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id})
                                    app.mk.queue._reindex()
                                    app.selectedMediaItems = []
                                }
                            },
                            {
                                "id": "addToPlaylist",
                                "name": "Add to Playlist...",
                                "action": function () {
                                    app.promptAddToPlaylist()
                                }
                            },
                            {
                                "id": "love",
                                "name": "Love",
                                "disabled": true,
                                "action": function () {
                                    app.love(self.item)
                                }
                            },
                            {
                                "id": "unlove",
                                "name": "Unlove",
                                "disabled": true,
                                "action": function () {
                                    app.unlove(self.item)
                                }
                            },
                            {
                                "id": "dislike",
                                "name": "Dislike",
                                "disabled": true,
                                "action": function () {
                                    app.dislike(self.item)
                                }
                            },
                            {
                                "id": "undo_dislike",
                                "name": "Undo dislike",
                                "disabled": true,
                                "action": function () {
                                    app.unlove(self.item)
                                }
                            },
                            {
                                "name":  (this.addedToLibrary) ? "Remove from Library..." : "Add to Library...",
                                "action": async function () {
                                    let item_id = self.item.attributes.playParams.id ?? self.item.id;
                                    let data_type = self.item.attributes.playParams.kind ?? self.item.type;
                                    if (self.addedToLibrary != true)  { console.log("add"); app.addToLibrary(item_id); self.addedToLibrary = true} 
                                    else { console.log("remove"); await self.removeFromLibrary(item_id); self.addedToLibrary = false};
                                }
                            },

                        ]
                    }
                }
                let rating = await app.getRating(self.item)
                if(rating == 0) {
                    menus.normal.items.find(x => x.id == 'love').disabled = false
                    menus.normal.items.find(x => x.id == 'dislike').disabled = false
                }else if(rating == 1) {
                    menus.normal.items.find(x => x.id == 'unlove').disabled = false
                }else if(rating == -1) {
                    menus.normal.items.find(x => x.id == 'undo_dislike').disabled = false
                }
                if ((self.item.attributes.playParams.kind ?? self.item.type).includes("playlist")) {
                    // remove the add to playlist option by id "addToPlaylist" using the .filter() method
                    menus.normal.items = menus.normal.items.filter(function (item) {
                        return item.id != "addToPlaylist"
                    })
                }
                CiderContextMenu.Create(event, menus[useMenu])
            },
        }
    });
</script>