package api

import (
	"fmt"
	"log"
	"net/http"
	"sync"

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

	"golang.org/x/net/context"
)

func (s *Server) sunsetJob(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	go s.sunset()

	s.serveSuccess(w, "sunset")
}

func (s *Server) sunset() {
	log.Printf("starting sunset")

	idCh, errCh := s.backend.ScanAnnotationsEnabledUsersAll()
	ids := []string{}

loop:
	for {
		select {
		case id, more := <-idCh:
			if !more {
				break loop
			}
			ids = append(ids, id)
		case err := <-errCh:
			if err != nil {
				s.logError(fmt.Errorf("scan error on sunset: %v", err))
				return
			}

		}
	}

	log.Printf("found %v users to clean up", len(ids))
	s.stats.Gauge("sunset.users", int64(len(ids)), 1.0)

	var wg sync.WaitGroup
	wg.Add(numWorkers)

	done := 0
	ch := make(chan string, numWorkers)
	for i := 0; i < numWorkers; i++ {
		go func() {
			defer wg.Done()
			for id := range ch {
				err := s.backend.DisableAnnotations(context.Background(), id)
				if err != nil {
					s.logError(fmt.Errorf("(sunset) failed to disable annotation for %v: %v", id, err))
				}

				if err := s.yt.SetYoutubeAnnotationsStatus(context.Background(), id, youtube.StatusDown); err != nil {
					s.logError(fmt.Errorf("(sunset) failed to clean up annotation for %v: %v", id, err))
				}
				done++
			}
		}()
	}

	for _, id := range ids {
		ch <- id
	}
	close(ch)
	wg.Wait()

	// Report results
	log.Printf("done sunset: %v", done)
	s.stats.Gauge("sunset.done", int64(done), 1.0)
}
