package api

import (
	"fmt"
	"net/http"

	"code.justin.tv/live/yt-live-annotations/youtube"

	"goji.io/pat"
	"golang.org/x/net/context"
)

// getExistingAnnotations
func (s *Server) getExistingAnnotations(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := pat.Param(ctx, "user_id")

	annotations, err := s.yt.GetYoutubeAnnotations(ctx, userID)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("yt get (%v): %v", userID, err), "get_annotations")
		return
	}

	if annotations != nil {
		s.serveSuccess(w, annotations, "get_annotations")
	} else {
		s.serveError(w, r, http.StatusNotFound, fmt.Errorf("no annotations found"), "get_annotations")
	}
}

// addAnnotation
func (s *Server) addAnnotation(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := pat.Param(ctx, "user_id")

	err := s.yt.SetYoutubeAnnotationsStatus(ctx, userID, youtube.StatusUp)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("yt add (%v): %v", userID, err), "add_annotation")
		return
	}

	s.serveSuccess(w, "OK", "add_annotation")
}

// removeAnnotation
func (s *Server) removeAnnotation(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := pat.Param(ctx, "user_id")

	err := s.yt.SetYoutubeAnnotationsStatus(ctx, userID, youtube.StatusDown)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("yt remove (%v): %v", userID, err), "remove_annotation")
		return
	}

	s.serveSuccess(w, "OK", "remove_annotation")
}

// clearAllAnnotations
func (s *Server) clearAllAnnotations(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := pat.Param(ctx, "user_id")

	err := s.yt.ClearYoutubeAnnotations(ctx, userID)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("yt clear (%v): %v", userID, err), "clear_annotations")
		return
	}

	s.serveSuccess(w, "OK", "clear_annotations")
}
