// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

package ocdav

import (
	"encoding/hex"
	"net/http"

	"github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/config"
	"github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/net"
	"github.com/opencloud-eu/reva/v2/pkg/appctx"
	"github.com/opencloud-eu/reva/v2/pkg/rhttp/router"
)

// AvatarsHandler handles avatar requests
type AvatarsHandler struct {
}

func (h *AvatarsHandler) init(c *config.Config) error {
	return nil
}

// Handler handles requests
func (h *AvatarsHandler) Handler(s *svc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		log := appctx.GetLogger(ctx)

		if r.Method == http.MethodOptions {
			// no need for the user, and we need to be able
			// to answer preflight checks, which have no auth headers
			r.URL.Path = "/" // always use / ... we just want the options answered so phoenix doesnt hiccup
			s.handleOptions(w, r)
			return
		}

		_, r.URL.Path = router.ShiftPath(r.URL.Path)
		if r.Method == http.MethodGet && r.URL.Path == "/128.png" {
			// TODO load avatar url from user context?
			const img = "[encoded data, 4810 characters]"
			decoded, err := hex.DecodeString(img)
			if err != nil {
				log.Error().Err(err).Msg("error decoding string")
				w.WriteHeader(http.StatusInternalServerError)
			}
			w.Header().Set(net.HeaderContentType, "image/png")
			if _, err := w.Write(decoded); err != nil {
				log.Error().Err(err).Msg("error writing data response")
			}
			return
		}

		w.WriteHeader(http.StatusNotFound)
	})
}
