//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017-2019 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  tank is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with tank. If not, see <http://www.gnu.org/licenses/>.
//

package v1

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gitlab.servus.at/autoradio/tank/store"
)

func (api *API) ListShows(c *gin.Context) {
	storeShows, err := api.store.ListShows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	s := getAuthSession(c.Request) // this will panic if there is no session
	showsMap := make(map[string]store.Show)
	for _, showName := range s.Shows {
		showsMap[showName] = store.Show{Name: showName}
	}
	for _, show := range storeShows {
		if _, ok := showsMap[show.Name]; ok || s.AllShows {
			showsMap[show.Name] = show
		}
	}
	result := ShowsListing{}
	for _, show := range showsMap {
		result.Shows = append(result.Shows, show)
	}

	c.JSON(http.StatusOK, result)
}

func (api *API) CreateShow(c *gin.Context) {
	// TODO: implement clone depending on query parameter
	showID := c.Param("show-id")
	if authorized, _ := authorizeRequest(c, showID); !authorized {
		return
	}

	show, err := api.store.CreateShow(showID)
	if err != nil {
		sendError(c, err)
		return
	}
	c.JSON(http.StatusCreated, show)
}