package sync

import (
	"bufio"
	"io"
	"net/url"
	"os"
	"regexp"
)

var gitRemoteRe = regexp.MustCompile(`^(?:(?:git@|https://)([\w.@]+)(?:/|:))((?:[\w-_]+)/(?:[\w-_/]+))(?:.git){0,1}(?:(?:/){0,1})$`)

func countFileInDir(dirname string) (int, error) {
	files, err := os.ReadDir(dirname)
	if err != nil {
		return 0, err
	}

	return len(files), nil
}

func (i GitImporter) exists(filename string) bool {
	return i.li.exists(filename)
}

func (i GitImporter) toURL(filename string) string {
	return i.li.toURL(filename)
}

func (i GitImporter) GetLocalPath(filename ...string) string {
	return i.li.GetLocalPath(filename...)
}

func (i GitImporter) importFile(URI string, next func(string, string) (interface{}, error)) (interface{}, error) {
	return i.li.importFile(URI, next)
}

func (i GitImporter) getFile(filename string, writer *bufio.Writer) error {
	return i.li.getFile(filename, writer)
}

func (i GitImporter) writeFile(filename string, reader io.Reader) error {
	return i.li.writeFile(filename, reader)
}

func (i GitImporter) listDir(filename string) ([]string, error) {
	return i.li.listDir(filename)
}

func (i GitImporter) stat(filename string) (os.FileInfo, error) {
	return i.li.stat(filename)
}

func (i GitImporter) Kind() string {
	return "git originated from " + i.Remote + " on " + i.li.Kind()
}

func getForgeBaseLink(remote string) (u *url.URL, err error) {
	res := gitRemoteRe.FindStringSubmatch(remote)
	u, err = url.Parse(res[2])
	u.Scheme = "https"
	u.Host = res[1]
	return
}
