package notes

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func (s *Server) edit(w http.ResponseWriter, r *http.Request) {
	p := NewPathFromURL(r.URL.Path)
	if p.IsDir() {
		http.NotFound(w, r)
		return
	}
	head(w, r)
	editHead(w, p)
	editFile(w, p)
	foot(w, r)
}

func editHead(w http.ResponseWriter, p Path) {
	fmt.Fprintln(w, h2(p.MultiLink()))
}

func editFile(w http.ResponseWriter, p Path) {
	href := p.HREF
	href = strings.TrimPrefix(href, "/")
	hrefs := strings.SplitN(href, "/", 2)
	href = hrefs[0]
	if len(hrefs) > 1 {
		href = hrefs[1]
	}
	b, _ := ioutil.ReadFile(p.Local)
	fmt.Fprintf(w, `
      <form action="/submit/%s" method="post" style="width:100%%; height: 90%%">
         <table style="width:100%%; height: 90%%">
            <textarea name="content" style="width:100%%; min-height:90%%">%s</textarea>
         </table>
         <button type="submit">Submit</button>
      </form>
   `, href, b)
}
