//
//  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"
)

func (api *API) ListImportsOfShow(c *gin.Context) {
	showID := c.Param("show-id")
	if authorized, _ := authorizeRequest(c, showID); !authorized {
		return
	}

	jobs, err := api.importer.ListJobs(showID)
	if err != nil {
		sendError(c, err)
		return
	}
	c.JSON(http.StatusOK, JobsListing{jobs})
}

func (api *API) ReadImportOfFile(c *gin.Context) {
	showID := c.Param("show-id")
	if authorized, _ := authorizeRequest(c, showID); !authorized {
		return
	}

	id, err := idFromString(c.Param("file-id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: "invalid file-id: " + err.Error()})
		return
	}

	waitFor := c.Query("wait-for")
	switch waitFor {
	case "running":
	case "done":
	case "":
	default:
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: "unable to wait for unknown state: " + waitFor})
		return
	}

	job, err := api.importer.GetJob(showID, id)
	if err != nil {
		// TODO: return import info from store if err == ErrNotFound
		sendError(c, err)
		return
	}

	switch waitFor {
	case "running":
		<-job.Running()
	case "done":
		<-job.Done()
	}
	c.JSON(http.StatusOK, job)
}

func (api *API) CancelImportOfFile(c *gin.Context) {
	showID := c.Param("show-id")
	if authorized, _ := authorizeRequest(c, showID); !authorized {
		return
	}

	id, err := idFromString(c.Param("file-id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: "invalid file-id: " + err.Error()})
		return
	}
	job, err := api.importer.GetJob(showID, id)
	if err != nil {
		sendError(c, err)
		return
	}
	job.Cancel()
	c.JSON(http.StatusNoContent, nil)
}