package pages

import (
	"net/http"
	"os"
	"fmt"
	"bytes"

	"forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors"

	"keikos.work/templates/layouts"
)

var WEBHOOK_URL = os.Getenv("WEBHOOK_URL")
var EYE_RESPONSE = os.Getenv("EYE_RESPONSE")

func init() {
	if WEBHOOK_URL == "" {
		panic("missing WEBHOOK_URL variable")
	}
	if EYE_RESPONSE == "" {
		panic("missing EYE_RESPONSE variable")
	}
}

type Eye struct{}

func (p *Eye) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		if err := p.page(nil).Render(r.Context(), w); err != nil {
			rerrors.InternalError(err).ServeHTTP(w, r)
		}
		return
	}

	response := r.FormValue("response")
	if response != EYE_RESPONSE {
		f := false
		if err := p.page(&f).Render(r.Context(), w); err != nil {
			rerrors.InternalError(err).ServeHTTP(w, r)
		}

		_, _ = http.Post(WEBHOOK_URL, "application/json", bytes.NewReader([]byte(fmt.Sprintf(`
{
  "content": null,
  "embeds": [
    {
      "title": "New INCORRECT Response",
      "description": "Response %s",
      "color": 16750848
    }
  ],
  "username": "Eye",
  "attachments": []
}
	`, response))))
		return
	}

	t := true
	if err := p.page(&t).Render(r.Context(), w); err != nil {
		rerrors.InternalError(err).ServeHTTP(w, r)
	}

	message := r.FormValue("message")
	if message == "" {
		message = "EMPTY MESSAGE"
	}

	_, _ = http.Post(WEBHOOK_URL, "application/json", bytes.NewReader([]byte(fmt.Sprintf(`
{
  "content": null,
  "embeds": [
    {
      "title": "New Response",
      "description": "Message %s",
      "color": 16750848
    }
  ],
  "username": "Eye",
  "attachments": []
}
	`, message))))
}

templ (p *Eye) page(correct *bool) {
	@layouts.Page(layouts.PageInfo{}) {
		<main class="w-100vw h-100vh absolute top-0 left-0 flex justify-center items-center">
			<div class="text-center px-10 text-gray-500">
				<p class="font-mono text-justify">
					{ `"§ \+ •|*|∆} ¥^ \§+ √^{∆√∆^: §+ {+π|{§| ∆^ √§+, ∆√|€∆ •∆} §}\{§¢∆} •§` }
					<span class="bg-current">########</span>
					{ `§$∆¢\∆}§| ^ €§+ \{^¥^, § ¥^ €^¥\§ •∆ √^¥~}§~∆√∆^ €§ ∆}}§¥\∆{§|, ∆^} ¢∆•^} •^ ¥•}\§"` }
				</p>
				<form method="post">
					<input type="text" required name="response" placeholder="00:00-00" class="text-gray-500 bg-transparent border-0 border-b-1"/>
					<input type="text" name="message" placeholder="Message" class="text-gray-500 bg-transparent border-0 border-b-1"/>
					<button class="bg-transparent border-0 text-gray-500 border-b-1">Submit</button>
				</form>
				if correct != nil {
					if *correct {
						<p class="text-green-500">
							Correct
						</p>
					} else {
						<p class="text-red-500">
							Incorrect
						</p>
					}
				}
			</div>
		</main>
	}
}
