package main

import (
	"fmt"
	"log"
	"os"
	"mime"
	"net/http"
	"strconv"
	"path"
	"path/filepath"
	"sort"
)

const pageSize = 5

func imgs(w http.ResponseWriter, r *http.Request) {
	u, err := checkSession(w, r)
	if u != nil && err == nil {
		username := u.Username
		if u.IsAdmin {
			name := r.URL.Query().Get("user")
			if name != "" {
				username = name
			}
		}
		fragment := r.URL.Query().Has("fragment")
		pageQuery := r.URL.Query().Get("page")
		if pageQuery == "" {
			pageQuery = "0"
		}
		page, err := strconv.Atoi(pageQuery)
		if err != nil {
			sendError(w, r, err.Error(), http.StatusInternalServerError)
			return
		}
		userDocPath := filepath.Join(baseDocDir, username)
		err = os.Mkdir(userDocPath, 0750)
		if err != nil && !os.IsExist(err) {
			sendError(w, r, err.Error(), http.StatusInternalServerError)
			return
		}
		//files, err := os.ReadDir(userDocPath)
		//if err != nil {
		//	sendError(w, r, err.Error(), http.StatusInternalServerError)
		//	return
		//}
		//sort.Slice(files, func(i, j int) bool {
		//	info1, err := files[i].Info()
		//	if err != nil {
		//		return false
		//	}
		//	info2, err := files[j].Info()
		//	if err != nil {
		//		return false
		//	}
		//	return info1.ModTime().After(info2.ModTime())
		//})
		start := page * pageSize
		//imgs := extractImgs(files, start)
		imgs, err := extractImgsGlob(userDocPath)
		if err != nil {
			sendError(w, r, err.Error(), http.StatusInternalServerError)
			return
		}
		sort.Slice(imgs, func(i, j int) bool {
			return imgs[i].ModTime.After(imgs[j].ModTime)
		})
		end := start + pageSize
		if end > len(imgs) {
			end = len(imgs)
		}
		if start > len(imgs) {
			start = len(imgs)
		}
		flasherr := consumeFlash(w, r, "error")
		userImpersonation := r.URL.Query().Get("user")
		data := struct {
			Imgs []Doc
			Start int
			End int
			NbFiles int
			Page int
			Error string
			UserImpersonation string
		}{
			imgs[start:end],
			start + 1,
			end,
			len(imgs),
			page,
			flasherr,
			userImpersonation,
		}
		if fragment {
			//serveSimple(w, r, data, "templates/imgs_stub.html")
			serveSimple(w, r, data, "templates/imgs_page.html", "templates/imgs_stub.html")
		} else {
			serveTemplate(w, r, data, "templates/imgs_page.html", "templates/imgs.html")
		}
		return
	} else if err != nil {
		log.Println(err)
	}
	sendFlash(w, r, "redirect", r.URL.String())
	http.Redirect(w, r, "/login", http.StatusSeeOther)
}

func extractImgsGlob(userDocPath string) ([]Doc, error) {
	var typs []string = []string {
		"image/jpeg",
		"image/png",
		"image/gif",
		"image/avif",
		"image/bmp",
		"image/vnd.microsoft.icon",
		"image/svg+xml",
		"image/tiff",
		"image/webp",
	}
	var exts []string
	for _, typ := range typs {
		e, err := mime.ExtensionsByType(typ)
		if err != nil {
			return nil, err
		}
		exts = append(exts, e...)
	}
	var imgs []Doc
	for _, ext := range exts {
		glob := fmt.Sprintf("*%s", ext)
		p := filepath.Join(userDocPath, glob)
		matches, err := filepath.Glob(p)
		if err != nil {
			return nil, err
		}
		for _, match := range matches {
			info, err := os.Stat(match)
			if err != nil {
				return nil, err
			}
			imgs = append(imgs, Doc {
				info.Name(),
				humanize(info.Size()),
				info.ModTime(),
				path.Join(userDocPath, info.Name()),
			})
		}
	}
	return imgs, nil
}

//func extractImgsPaged(files []fs.DirEntry, start int) []Doc {
//	var typs []string = []string {
//		"image/jpeg",
//		"image/png",
//		"image/gif",
//		"image/avif",
//		"image/bmp",
//		"image/vnd.microsoft.icon",
//		"image/svg+xml",
//		"image/tiff",
//		"image/webp",
//	}
//	var exts []string
//	for _, typ := range typs {
//		e, err := mime.ExtensionsByType(typ)
//		if err != nil {
//			sendError(w, r, err.Error(), http.StatusInternalServerError)
//			return
//		}
//		exts = append(exts, e...)
//	}
//	var imgs []Doc
//	var i int = 0
//	for _, file := range files {
//		if i >= start + pageSize {
//			break
//		}
//		for _, ext := range exts {
//			if strings.HasSuffix(file.Name(), ext) && i >= start {
//				info, err := file.Info()
//				if err != nil {
//					sendError(w, r, err.Error(), http.StatusInternalServerError)
//					return
//				}
//				imgs = append(imgs, Doc {
//					file.Name(),
//					humanize(info.Size()),
//					info.ModTime(),
//					path.Join(baseDocDir, u.User, file.Name()),
//				})
//				i++
//				break
//			}
//		}
//	}
//	return imgs
//}
