// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package http

import (
	"encoding/hex"
	"fmt"
	"html/template"
	"path"

	"github.com/ethereum/go-ethereum/swarm/api"
)

type htmlListData struct {
	URI  *api.URI
	List *api.ManifestList
}

var TemplatesMap = make(map[string]*template.Template)
var faviconBytes []byte

func init() {
	for _, v := range []struct {
		templateName string
		partial      string
		funcs        template.FuncMap
	}{
		{
			templateName: "error",
			partial:      errorResponse,
		},
		{
			templateName: "bzz-list",
			partial:      bzzList,
			funcs: template.FuncMap{
				"basename": path.Base,
				"leaflink": leafLink,
			},
		},
		{
			templateName: "landing-page",
			partial:      landing,
		},
	} {
		TemplatesMap[v.templateName] = template.Must(template.New(v.templateName).Funcs(v.funcs).Parse(baseTemplate + css + v.partial + logo))
	}

	bytes, err := hex.DecodeString(favicon)
	if err != nil {
		panic(err)
	}
	faviconBytes = bytes
}

func leafLink(URI api.URI, manifestEntry api.ManifestEntry) string {
	return fmt.Sprintf("/bzz:/%s/%s", URI.Addr, manifestEntry.Path)
}

const bzzList = `{{ define "content" }}
<h3 class="top-space">Swarm index of {{ .URI }}</h3>
<hr>
<table>
  <thead>
    <tr>
      <th>Path</th>
      <th>Type</th>
      <th>Size</th>
    </tr>
  </thead>

  <tbody>
    {{ range .List.CommonPrefixes }}
    <tr>
      <td>
        <a class="normal-link" href="{{ basename . }}/">{{ basename . }}/</a>
      </td>
      <td>DIR</td>
      <td>-</td>
    </tr>
    {{ end }}
    {{ range .List.Entries }}
    <tr>
      <td>
        <a class="normal-link" href="{{ leaflink $.URI . }}">{{ basename .Path }}</a>
      </td>
      <td>{{ .ContentType }}</td>
      <td>{{ .Size }}</td>
    </tr>
    {{ end }}
</table>
<hr>

 {{ end }}`

const errorResponse = `{{ define "content" }}
<div class="container">
    <div class="logo">
        {{ template "logo" . }}
    </div>

    <div class="separate-block">
      <h3>{{.Msg}}</h3>
    </div>

    <div>
      <h5>Error code: {{.Code}}</h5>
    </div>

    <div class="footer">
      <p>{{.Timestamp}}</p>
      <p>Swarm: Serverless Hosting Incentivised Peer-To-Peer Storage And Content Distribution</p>
    </div>
  </div>
{{ end }}`

const landing = `{{ define "content" }}

<script type="text/javascript">
function goToPage() {
  var page = document.getElementById('page').value;
  if (page == "") {
    var page = "theswarm.eth"
  }
  var address = "/bzz:/" + page;
  location.href = address;
  console.log(address)
}
</script>

<div class="container">
<div class="logo">
  {{ template "logo" . }}
</div>


<div class="searchbar">
  <form class="separate-block" action="javascript:goToPage();">
    <input type="text" id="page" autofocus name="search" placeholder="Please enter an ENS name or swarm hash to retrieve ..">
    <button class="button" type="submit" value="submit" onclick="goToPage();">Go!</button>
  </form>
</div>
<div class="footer">
<p>{{.Timestamp}}</p>
<p>Swarm: Serverless Hosting Incentivised Peer-To-Peer Storage And Content Distribution</p>
</div>
</div>
  
{{ end }}`

const baseTemplate = `<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
  <meta http-equiv="X-UA-Compatible" ww="chrome=1"/>
  <link rel="icon" type="image/x-icon" href="favicon.ico"/>
  <style>
  {{ template "css" . }}
  </style>
</head>
<body>
  {{ template "content" . }}
</body>
</html>
`

const css = `{{ define "css" }} 
html {
  font-size: 18px;
  font-size: 1.13rem;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  font-family: Helvetica, Arial, sans-serif;
}

body {
  background: #f6f6f6;
  color: #333;
}

a, a:visited, a:active {
  color: darkorange;
}

a.normal-link, a.normal-link:active { color: #0000EE; }
a.normal-link:visited { color: #551A8B; }

table {
  border-collapse: separate;
}

td {
  padding: 3px 10px;
}


.container {
  max-width: 600px;
  margin: 40px auto 40px;
  text-align: center;
}

.separate-block {
  margin: 40px 0;
  word-wrap: break-word;
}

.footer {
  font-size: 12px;
  font-size: 0.75rem;
  text-align: center;
}

.orange {
  color: #ffa500;
}

.top-space {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* SVG Logos, editable */

.searchbar {
  padding: 20px 20px 0;
}

.logo {
  margin: 100px 80px 0;
}

.logo a img {
  max-width: 140px;
}

/* Tablet < 600p*/

@media only screen and (max-width: 600px) {}

/* Mobile phone < 360p*/

@media only screen and (max-width: 360px) {
  h1 {
      font-size: 20px;
      font-size: 1.5rem;
  }
  h2 {
      font-size: 0.88rem;
      margin: 0;
  }
  .logo {
      margin: 50px 40px 0;
  }
  .footer {
      font-size: 0.63rem;
      text-align: center;
  }
}

input[type=text] {
  width: 100%;
  box-sizing: border-box;
  border: 2px solid #777;
  border-radius: 2px;
  font-size: 16px;
  padding: 12px 20px 12px 20px;
  transition: border 250ms ease-in-out;
}

input[type=text]:focus {
  border: 2px solid #ffce73;
}

.button {
  background-color: #ffa500;
  margin: 20px 0;
  border: none;
  border-radius: 2px;
  color: #222;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
{{ end }}`

const logo = `{{ define "logo" }} 
<a href="/bzz:/theswarm.eth"><img src="data:image/png;base64,[encoded data, 31312 characters]"/></a>
{{ end }}`

const favicon = `[encoded data, 64076 characters]`
