//
//  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 (
	"io/ioutil"
	"log"

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

type API struct {
	store    *store.Store
	importer *importer.Importer
	infoLog  *log.Logger
	errLog   *log.Logger
	dbgLog   *log.Logger
}

func NewAPI(st *store.Store, im *importer.Importer, infoLog, errLog, dbgLog *log.Logger) (api *API) {
	if infoLog == nil {
		infoLog = log.New(ioutil.Discard, "", 0)
	}
	if errLog == nil {
		errLog = log.New(ioutil.Discard, "", 0)
	}
	if dbgLog == nil {
		dbgLog = log.New(ioutil.Discard, "", 0)
	}

	api = &API{}
	api.store = st
	api.importer = im
	api.infoLog = infoLog
	api.errLog = errLog
	api.dbgLog = dbgLog
	return
}

func InstallHTTPHandler(r *gin.RouterGroup, st *store.Store, im *importer.Importer, infoLog, errLog, dbgLog *log.Logger) {
	r.Use(auth.Middleware())
	api := NewAPI(st, im, infoLog, errLog, dbgLog)

	// Shows
	shows := r.Group("shows")
	{
		shows.GET("", api.ListShows)
		shows.POST(":show-id", api.CreateShow)
		shows.GET(":show-id/imports", api.ListImportsOfShow)

		// Show/Files
		files := shows.Group(":show-id/files")
		{
			files.GET("", api.ListFilesOfShow)
			files.POST("", api.CreateFileForShow)
			files.GET(":file-id", api.ReadFileOfShow)
			files.PATCH(":file-id", api.PatchFileOfShow)
			files.DELETE(":file-id", api.DeleteFileOfShow)

			files.GET(":file-id/usage", api.ReadUsageOfFile)
			files.GET(":file-id/import", api.ReadImportOfFile)
			files.DELETE(":file-id/import", api.CancelImportOfFile)

			// TODO: distignuish between flow.js and simple upload using the content type?!?
			files.PUT(":file-id/upload", api.UploadFileSimple)
			files.POST(":file-id/upload", api.UploadFileFlowJS)
			files.GET(":file-id/upload", api.TestFileFlowJS)
		}

		// Show/Playlists
		playlists := shows.Group(":show-id/playlists")
		{
			playlists.GET("", api.ListPlaylistsOfShow)
			playlists.POST("", api.CreatePlaylistForShow)
			playlists.GET(":playlist-id", api.ReadPlaylistOfShow)
			playlists.PUT(":playlist-id", api.UpdatePlaylistOfShow)
			playlists.DELETE(":playlist-id", api.DeletePlaylistOfShow)
		}
	}
}