package api

import (
	"fmt"
	"net/http"

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

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

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

	enabled, err := s.backend.GetAnnotationsEnabled(ctx, userID)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("failed to get annotations status"), "set_annotations_disabled")
		return
	}

	s.serveSuccess(w, map[string]bool{"enabled": enabled}, "get_annotations_enabled")
}

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

	err := s.backend.EnableAnnotations(ctx, userID)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("failed to enable live annotations"), "set_annotations_disabled")
		return
	}

	s.serveSuccess(w, map[string]bool{"enabled": true}, "set_annotations_enabled")
}

// setAnnotationsDisabled
func (s *Server) setAnnotationsDisabled(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := pat.Param(ctx, "user_id")
	err := s.backend.DisableAnnotations(ctx, userID)
	if err != nil {
		s.serveError(w, r, http.StatusInternalServerError, fmt.Errorf("failed to disable live annotations"), "set_annotations_disabled")
		return
	}

	err = s.yt.SetYoutubeAnnotationsStatus(ctx, userID, youtube.StatusDown)
	if err != nil && s.errorLogger != nil {
		s.serveError(w, r, http.StatusOK, fmt.Errorf("yt status down err (%v): %v", userID, err), "set_annotations_disabled")
		return
	}

	s.serveSuccess(w, map[string]bool{"enabled": false}, "set_annotations_disabled")
}
