/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  getFinalHandler.go
 *     Version:    1.0.0
 *     Date:       2018-01-14
 *
 *     Autor:      Bogdanovic Theodor
 *     Contact:    t.bogdanovic@hotmail.com
 *
 *     License:    GPLv3
 *
 **************************************************************************************/
/**************************************************************************************
 * Copyright 2018 Bogdanovic Theodor
 *
 * This file is part of kvmstoreserver.
 *
 * kvmstoreserver is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * kvmstoreserver 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with kvmstoreserver.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************************/
/**************************************************************************************
 *  Further explanations:  This source code is under the license specified by the
 *                         Autor above. Core components or other packages are still
 *                         in source code form, under the license specified by the
 *                         respective author.
 **************************************************************************************/

package finalHandlers

import (
	"encoding/json"
	es "essentials"
	bth "kvmstoreserver_utils/bTreeHandling"
	eh "kvmstoreserver_utils/errorHandling"
	knh "kvmstoreserver_utils/keyNameHandling"
	"net/http"
	"net/url"
	"strconv"

	log "github.com/judwhite/logrjack"
)

//*****************************************************************************
//*
//*      Public Functions: Final Handler
//*
//*****************************************************************************

// GetFinalHandler includes all the logic to get a document, a document
// by revision or a specific key back.
//
// The logic is equivalent to the use -Zurueckliefern-
func GetFinalHandler(w http.ResponseWriter, r *http.Request) {

	defer eh.Try("FinalHandler->GetFinalHandler()")
	es.InjectJSONTypeToHeader(w)

	var (
		revNbrInt            *int
		jsonOutput           interface{}
		handlerRuntimeErrors error
	)

	parsedKeyName, errKeyParser := url.PathUnescape(
		es.CutKeyFromURL(r.RequestURI))

	eh.IfErrBuildJSONAndOrPanic(w, errKeyParser, http.StatusBadRequest,
		"Invalid character in key name", es.DoPanic)

	keyCtx, errKeyName := knh.NewKeyContext(parsedKeyName)

	eh.IfErrBuildJSONAndOrPanic(w, errKeyName, http.StatusBadRequest,
		"Error by Key to=> ID mapping - Maybe forget the name?", es.DoPanic)

	errMember := bth.NewBtree().Member(keyCtx)
	eh.IfErrBuildJSONAndOrPanic(w, errMember, http.StatusBadRequest,
		"It seems that the key does not exist", es.DoPanic)

	if r.URL.Query().Get("rev") != "" {
		revNbr, parseIntErr := strconv.
			ParseInt(r.URL.Query().Get("rev"), 10, 32)

		eh.IfErrBuildJSONAndOrPanic(w, parseIntErr,
			http.StatusInternalServerError,
			"The revision number must be a number", es.DoPanic)

		parsedInt := int(revNbr)
		revNbrInt = &parsedInt
	}

	// If revNbrInt empty, then it is nil. GetModelOrDefault() returns by a
	// nil *int the last entry (current revison)
	model, errModelSearch := bth.NewBtree().Get(keyCtx).GetModelOrDefault(revNbrInt)
	eh.IfErrBuildJSONAndOrPanic(w, errModelSearch, http.StatusBadRequest,
		"Is this revision number really correct?", es.DoPanic)

	searchOnject := r.URL.Query().Get("search")
	if searchOnject != "" {
		jsonOutput, handlerRuntimeErrors = model.Search(searchOnject)
		eh.IfErrBuildJSONAndOrPanic(w, handlerRuntimeErrors, http.StatusBadRequest,
			"It seems like the search term is wrong, please check it again", es.DoPanic)
	} else {
		jsonOutput = model.Data
	}

	output, handlerRuntimeErrors := json.Marshal(jsonOutput)

	eh.IfErrBuildJSONAndOrPanic(w, handlerRuntimeErrors,
		http.StatusInternalServerError,
		"Error by converting cotent into a JSON structure", es.DoPanic)

	log.Infof("Successful reply sent -> (ID: %v) | (Key name: %v) | (RevNbr: %v) -> send back to (Client: %v)",
		keyCtx.GetNodeID(), keyCtx.GetKeyStrName(), model.RevNbr, r.RemoteAddr)

	w.Write(output)
}
