package caddyhugo

import (
	"fmt"
	"image"
	"io"
	"net/http"
	"path"
	"strings"

	"git.stephensearles.com/stephen/caddy-hugo2/media"
)

func (ch *CaddyHugo) uploadMedia(w http.ResponseWriter, r *http.Request) (int, error) {
	if ch.Media == nil {
		http.NotFound(w, r)
		return 404, nil
	}

	mr, err := r.MultipartReader()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return 400, nil
	}

	for {
		part, err := mr.NextPart()
		if err == io.EOF {
			break
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return 400, nil
		}

		name := part.FileName()
		if name != "" {
			err = ch.Media.ReceiveNewMedia(name, part)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return 500, nil
			}
		}
	}

	return 200, nil
}

func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int, error) {
	if ch.Media == nil {
		http.NotFound(w, r)
		return 404, nil
	}

	io.WriteString(w, `<html>
	<head><style>
	iframe { height: 100%; }
	.img { display: inline-block; text-align: center; max-width: 19.9vw; min-height: 120px;}
	.img.selected { background-color: lightblue; }
	.copy { cursor: pointer; }
	@media (max-width: 800px) {
		.img {
			width: 50%;
			max-width: 50%;
		}
		body {
			min-height: 300px;
		}
	}
	</style></head>
	<body>
	<div style="position: fixed; top: 0; height: 10vh; width: 100%; background-color: white;">
	`)
	io.WriteString(w, UploadPage("media"))

	io.WriteString(w, `</div>
	<div style="display: inline-block; width: 100%; height: 10vh;"></div>
	`)
	if ch.Media != nil {
		mm, err := ch.Media.Walk()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return 500, nil
		}

		for _, m := range media.Set(mm).ByDate() {

			src, size, err := ch.Media.ThumbMax(*m, 100)
			if err != nil {
				fmt.Fprintf(w, `<div class="img">error rendering %q: %v</div>`, m.Name, err)
				continue
			}
			fmt.Fprintf(w, `<div class="img"><img width=%d height=%d src=%q data-filename=%q /><br /><input type="text" readonly value=%q /><span class="copy">&#x1F4CB;</span></div>`, size.Dx(), size.Dy(), src, m.Name, src)
		}
	}
	io.WriteString(w, `<script>
	document.querySelector('body').onclick = function (evt) {
		if (evt.target.tagName === "INPUT" && evt.target.type === "text") {
			evt.target.select();
		}
		if (evt.target.tagName === "SPAN" && evt.target.className === "copy") {
			evt.target.previousSibling.select();
			document.execCommand("copy");
		}
		if (evt.target.tagName === "IMG") {
			var current = document.querySelector(".img.selected");
			if (current) {
				current.classList = "img";
			}
			evt.target.parentElement.classList = "img selected";
			if (window.parent) {
				window.parent.postMessage(evt.target.dataset.filename, location.origin);
			}
		}
	}
	document.querySelector('body').onmouseup = function (evt) {
		if (evt.target.tagName === "INPUT" && evt.target.type === "text") {
			return false;
		}
	}
	</script></body><html>`)
	return 200, nil
}

func (ch *CaddyHugo) serveMedia(w http.ResponseWriter, r *http.Request) (int, error) {
	if ch.Media == nil {
		http.NotFound(w, r)
		return 404, nil
	}

	segs := strings.Split(r.URL.Path, "/")
	name := segs[len(segs)-1] // the last segment is the filename

	size := image.Rectangle{}

	m := ch.Media.ByName(name)

	if len(segs) >= 4 && len(segs) > 2 {
		var err error
		size, err = media.ParseSizeString(segs[len(segs)-2], m.Size)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return 400, nil
		}
	}

	file, err := ch.Media.Thumb(*m, size)
	if err != nil {
		http.Error(w, fmt.Sprintf("unable to load thumb"), http.StatusInternalServerError)
		return 500, nil
	}

	if file[0] == '/' {
		file = file[1:]
	}

	file = path.Join(ch.Media.ThumbDir, file)

	http.ServeFile(w, r, file)

	return 200, nil
}
