<script type="text/x-template" id="cider-home">
    <div class="content-inner home-page">
        <div v-if="page == 'main'">
            <div class="row">
                <div class="col">
                    <h3>{{app.getLz('home.recentlyPlayed')}}</h3>
                    <div class="well artistfeed-well">
                        <template v-if="isSectionReady('recentlyPlayed')">
                            <mediaitem-list-item v-for="item in recentlyPlayed.limit(6)"
                                                 :item="item"></mediaitem-list-item>
                        </template>
                        <div class="spinner" v-else></div>
                    </div>
                </div>
                <div class="col">
                    <div class="row nopadding">
                        <div class="col nopadding">
                            <h3>{{app.getLz('home.artistsFeed')}}</h3>
                        </div>
                        <div class="col-auto nopadding flex-center">
                            <button class="cd-btn-seeall" @click="app.appRoute('artist-feed')">{{app.getLz('term.seeAll')}}</button>
                        </div>
                    </div>
                    <div class="well artistfeed-well" style="margin-top:0;">
                        <template v-if="artistFeed.length > 0">
                            <mediaitem-list-item v-for="item in artistFeed.limit(6)" :item="item"></mediaitem-list-item>
                        </template>
                        <div class="spinner" v-else-if="followedArtists.length > 0"></div>
                        <div class="no-artist" v-else> {{app.getLz('home.artistsFeed.noArtist')}}</div>
                    </div>
                </div>
            </div>
            <!--            <div class="row" v-if="app.isDev">-->
            <!--                <div class="col">-->
            <!--                    <h3>Your Favorites</h3>-->
            <!--                    <div class="well">-->
            <!--                        <div class="hint-text" v-if="favorites.length == 0">Items you have added to your favorites will-->
            <!--                            appear here.-->
            <!--                        </div>-->
            <!--                        <mediaitem-scroller-horizontal kind="small" :items="favorites"-->
            <!--                                                       :item="item"></mediaitem-scroller-horizontal>-->
            <!--                    </div>-->
            <!--                </div>-->
            <!--            </div>-->
            <div class="row">
                <div class="col">
                    <h3>{{app.getLz('home.madeForYou')}}</h3>
                    <div class="well">
                        <template v-if="isSectionReady('madeForYou')">
                            <mediaitem-square kind="small" v-for="item in madeForYou" :item="item"></mediaitem-square>
                        </template>
                        <div class="spinner" v-else></div>
                    </div>
                </div>
            </div>
            <div class="row" v-if="friendsListeningTo && friendsListeningTo.length > 0">
                <div class="col">
                    <div class="row">
                        <div class="col nopadding">
                            <h3>{{app.getLz('home.friendsListeningTo')}}</h3>
                        </div>
                        <div class="col-auto nopadding flex-center">
                            <button class="cd-btn-seeall" @click="app.showSocialListeningTo()">{{app.getLz('term.seeAll')}}</button>
                        </div>
                    </div>
                    <div class="well">
                        <template v-if="isSectionReady('friendsListeningTo')">
                            <mediaitem-square kind="small" v-for="item in friendsListeningTo"
                                              :item="item"></mediaitem-square>
                        </template>
                        <div class="spinner" v-else></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

<script>
    Vue.component('cider-home', {
        template: '#cider-home',
        data: function() {
            return {
                app: this.$root,
                followedArtists: this.$root.cfg.home.followedArtists,
                favoriteItems: this.$root.cfg.home.favoriteItems,
                madeForYou: [],
                recentlyPlayed: [],
                friendsListeningTo: [],
                replayPlaylists: [],
                favorites: [],
                profile: {},
                modify: 0,
                artistFeed: [],
                showingArtistFeed: false,
                page: "main",
                sectionsReady: []
            }
        },
        async mounted() {
            let self = this
            this.getListenNowData()
            await this.getArtistFeed()
            await this.getFavorites()
        },
        methods: {
            isSectionReady(section) {
                return this.sectionsReady.includes(section)
            },
            removeFavoriteContext() {
                let self = this
                return {
                    name: "Remove from Favorites",
                    action: function(item) {
                        let index = self.favoriteItems.findIndex(x => x.id == item.id)
                        if (index > -1) {
                            self.favoriteItems.splice(index, 1)
                            self.app.cfg.home.favoriteItems = self.favoriteItems
                        }
                    }
                }
            },
            async getFavorites() {
                let self = this
                let libraryPlaylists = []
                let playlists = []
                for (let item of this.favoriteItems) {
                    if (item.type == "library-playlists") {
                        libraryPlaylists.push(item.id)
                    } else if (item.type == "playlists") {
                        playlists.push(item.id)
                    }
                }
                if (playlists.length != 0) {            
                    this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${playlists.toString()}`).then(playlistsData => {
                        self.favorites.push(...playlistsData.data)
                    })
                }
                if (libraryPlaylists.length != 0) {                    
                    this.app.mk.api.v3.music(`v1/me/library/playlists/${playlists.toString()}`).then(playlistsData => {
                        self.favorites.push(...playlistsData.data)
                    })
                }
            },
            async getArtistFeed() {
                let artists = this.followedArtists
                let self = this
                this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists?ids=${artists.toString()}&views=latest-release&include[songs]=albums&fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url,trackCount&limit[artists:top-songs]=2&art[url]=f`).then(artistData => {
                    artistData.data.data.forEach(item => {
                            if (item.views["latest-release"].data.length != 0) {
                                self.artistFeed.push(item.views["latest-release"].data[0])
                            }
                        })
                        // sort artistFeed by attributes.releaseDate descending, date is formatted as "YYYY-MM-DD"
                    this.artistFeed.sort((a, b) => {
                        let dateA = new Date(a.attributes.releaseDate)
                        let dateB = new Date(b.attributes.releaseDate)
                        return dateB - dateA
                    })
                })


            },
            getRecentlyPlayed() {

            },
            async getListenNowData() {
                let self = this
                this.app.mk.api.v3.music(`/v1/me/recommendations?timezone=${encodeURIComponent(app.formatTimezoneOffset())}&name=listen-now&with=friendsMix,library,social&art[social-profiles:url]=c&art[url]=c,f&omit[resource]=autos&relate[editorial-items]=contents&extend=editorialCard,editorialVideo&extend[albums]=artistUrl&extend[library-albums]=artistUrl,editorialVideo&extend[playlists]=artistNames,editorialArtwork,editorialVideo&extend[library-playlists]=artistNames,editorialArtwork,editorialVideo&extend[social-profiles]=topGenreNames&include[albums]=artists&include[songs]=artists&include[music-videos]=artists&fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url&fields[artists]=name,url&extend[stations]=airDate,supportsAirTimeUpdates&meta[stations]=inflectionPoints&types=artists,albums,editorial-items,library-albums,library-playlists,music-movies,music-videos,playlists,stations,uploaded-audios,uploaded-videos,activities,apple-curators,curators,tv-shows,social-upsells&platform=web`).then((data) => {
                    console.log(data.data.data[1])
                    try {
                        self.madeForYou = data.data.data.filter(section => {
                            if (section.meta.metrics.moduleType == "6") {
                                return section
                            };
                        })[0].relationships.contents.data
                    } catch (err) {}
                    self.sectionsReady.push("madeForYou")

                    try {
                        self.recentlyPlayed = data.data.data[1].relationships.contents.data
                        self.friendsListeningTo = data.data.data.filter(section => {
                            if (section.meta.metrics.moduleType == "11") {
                                return section
                            };
                        })[0].relationships.contents.data
                    } catch (err) {}
                    self.sectionsReady.push("recentlyPlayed")
                    self.sectionsReady.push("friendsListeningTo")
                });

                app.mk.api.v3.music("/v1/me/social/profile/").then((response) => {
                    self.profile = response.data.data[0]
                })

            }           
        }
    });
</script>