package web

import (
	"fmt"
	"net/http"
	"time"

	"github.com/Jaculabilis/intake/core"
	"github.com/Jaculabilis/intake/web/html"
)

func (env *Env) getChannels(writer http.ResponseWriter, req *http.Request) {
	allSources, err := core.GetSources(env.db)
	if err != nil {
		http.Error(writer, err.Error(), 400)
		return
	}

	channelSources, err := core.GetSourcesInChannel(env.db)
	if err != nil {
		http.Error(writer, err.Error(), 400)
		return
	}

	data := html.EditChannelsData{
		Sources:        allSources,
		ChannelSources: channelSources,
	}
	html.EditChannels(writer, data)
}

func (env *Env) editChannel(writer http.ResponseWriter, req *http.Request) {
	if err := req.ParseForm(); err != nil {
		http.Error(writer, err.Error(), 400)
		return
	}

	channel := req.Form.Get("channel")
	source := req.Form.Get("source")

	if channel == "" {
		http.Error(writer, "missing channel", 400)
		return
	}
	if source == "" {
		http.Error(writer, "missing source", 400)
		return
	}
	if exists, err := core.SourceExists(env.db, source); err != nil || !exists {
		http.Error(writer, fmt.Sprintf("could not find source %s: %v", source, err), 500)
		return
	}

	if req.Method == http.MethodPost {
		if err := core.AddSourceToChannel(env.db, channel, source); err != nil {
			http.Error(writer, err.Error(), 500)
			return
		}
		writer.Header()["HX-Refresh"] = []string{"true"}
		writer.WriteHeader(http.StatusNoContent)
		return
	}

	if req.Method == http.MethodDelete {
		if err := core.DeleteSourceFromChannel(env.db, channel, source); err != nil {
			http.Error(writer, err.Error(), 500)
			return
		}
		writer.Header()["HX-Refresh"] = []string{"true"}
		writer.WriteHeader(http.StatusNoContent)
		return
	}
}

func (env *Env) getChannel(writer http.ResponseWriter, req *http.Request) {
	channel := req.PathValue("channel")

	page := getQueryInt(req, "page", 1)
	count := getQueryInt(req, "count", core.DefaultFeedLimit)
	showHidden := getQueryInt(req, "hidden", 0)

	var items []core.Item
	var err error
	if showHidden != 0 {
		items, err = core.GetAllItemsForChannel(env.db, channel, (page-1)*count, count)
	} else {
		items, err = core.GetActiveItemsForChannel(env.db, channel, (page-1)*count, count)
	}
	if err != nil {
		http.Error(writer, err.Error(), 500)
		return
	}

	data := html.FeedData{
		Items:       items,
		ShowHidden:  showHidden,
		Page:        page,
		Count:       count,
		LastUpdated: time.Time{},
	}
	html.Feed(writer, data)
}