package youtube

import (
	"fmt"

	"google.golang.org/api/googleapi"
	"google.golang.org/api/youtube/v3"
)

const tooManyPromotedItemsError = "tooManyPromotedItems"

// client is an interface that simplifies the youtube golang api for consumption in this project
type client interface {
	ListChannels() (*youtube.ChannelListResponse, error)
	UpdateChannel(updatedChannel *youtube.Channel) error
	VideoExists(id string) (bool, error)
}

type ytClient struct {
	*youtube.Service
}

// TODO: wrap these client calls with timing stats
func (yt *ytClient) ListChannels() (*youtube.ChannelListResponse, error) {
	listCall := yt.Channels.List("invideoPromotion")
	listCall.Mine(true) //use the channel associated with the OAuth token
	return listCall.Do()
}

func (yt *ytClient) UpdateChannel(updatedChannel *youtube.Channel) error {
	updateCall := yt.Channels.Update("invideoPromotion", updatedChannel)
	_, err := updateCall.Do()
	if gErr, ok := err.(*googleapi.Error); ok {
		for _, e := range gErr.Errors {
			if e.Reason == tooManyPromotedItemsError {
				//TODO: do something here?
				return nil
			}
		}
	}
	return err
}

func (yt *ytClient) VideoExists(id string) (bool, error) {
	if id == "" {
		return false, nil
	}
	listCall := yt.Videos.List("id")
	listCall.Id(id)
	listResponse, err := listCall.Do()
	if err != nil {
		return false, fmt.Errorf("video exists error: %v", err)
	}
	return len(listResponse.Items) > 0, nil
}
