package validation

import (
	"errors"
	"fmt"
	"log"
	neturl "net/url"
	"strings"
)

// Errors
var (
	ErrNotAUrl = errors.New("not a URL")
	ErrIncorrectProtocol = errors.New("incorrect url protocol")
	ErrServiceUnsupported = errors.New("not a URL")
)

// Music hosts that we support
var musicHosts = []string{
	"youtube.com",
	"www.youtube.com",
}

func IsUrl(url string) (bool, *neturl.URL) {
	// If a URL has no scheme, this will fail.
	// So we'll add one if not present
	if !strings.Contains(url, "://") {
		url = fmt.Sprintf("https://%s", url)
	}

	parsed, err := neturl.ParseRequestURI(url) 

	return (err == nil), parsed
}

func IsMusicUrl(url string) (bool, error) {
	isUrl, parsed := IsUrl(url)

	if !isUrl {
		return false, ErrNotAUrl 
	}

	// If we have a scheme and it's not http/https we fail
	if parsed.Scheme != "" && !strings.Contains(parsed.Scheme, "http") {
		return false, ErrIncorrectProtocol
	}

	for _, host := range musicHosts {
		log.Println(parsed.Host)
		if host == parsed.Host {
			return true, nil
		}
	}

	return false, ErrServiceUnsupported
}