package main

import(
    "fmt"
    "log"
    "encoding/json"
    "os"
    "net/http"
    "net/url"
    "io/ioutil"
    "regexp"
)

var youtubeToken = os.Getenv("YOUTUBE_TOKEN")
var youtube_api = "https://www.googleapis.com/youtube/v3/search"
var youtube_video_baseurl = "https://youtube.com/watch?v="

func search_on_youtube(searchString string) (youtube_url string) {
    reg, _ := regexp.Compile("[^a-zA-Z0-9 -]+")
    processedString := reg.ReplaceAllString(searchString, "")
    t := &url.URL{Path: processedString}
    http_request := t.String()
    http_request_encoded := (youtube_api+"?part=snippet&maxResults=1&q="+http_request+"&key="+youtubeToken)

    response, err := http.Get(http_request_encoded)
    if err != nil {
        fmt.Printf("%s", err)
        os.Exit(1)
    } else {
        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        if err != nil {
            fmt.Printf("%s", err)
            os.Exit(1)
        }

        data := new(youtubeSearchResult)
        json.Unmarshal(contents, &data)

        if len(data.Items) > 0 {
            youtube_url = youtube_video_baseurl + data.Items[0].ID.VideoID
        } else {
            // TODO: put this spotify track on 'manual donwload queue'
            // youtube_url = "could not find track on yt"
            f, err := os.OpenFile("manual-download.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
            if err != nil {
                log.Fatal(err)
            }
            if _, err := f.Write([]byte(searchString+"\n")); err != nil {
                log.Fatal(err)
            }
            if err := f.Close(); err != nil {
                log.Fatal(err)
            }
        }
    }
    return
}
