/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  addFinalHandler.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"
	answer "kvmstoreserver_utils/HttpHandlers/essentials"
	bth "kvmstoreserver_utils/bTreeHandling"
	eh "kvmstoreserver_utils/errorHandling"
	knh "kvmstoreserver_utils/keyNameHandling"
	"net/http"
	"net/url"

	log "github.com/judwhite/logrjack"
)

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

// AddFinalHandler includes all the logic to add a document.
//
// The logic is equivalent to the use -Entgegennehmen-
func AddFinalHandler(w http.ResponseWriter, r *http.Request) {

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

	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)

	newModel := bth.DataModel{}
	newModel.MetaHeader = bth.NewMetaData(r)

	jsonDecoder := json.NewDecoder(r.Body)
	errDecode := jsonDecoder.Decode(&newModel.Data)
	eh.IfErrBuildJSONAndOrPanic(w, errDecode, http.StatusInternalServerError,
		"Please check the syntax of your JSON document, there is an error",
		es.DoPanic)

	currentRevNbr, errInsert := bth.NewBtree().Insert(keyCtx, &newModel)
	eh.IfErrBuildJSONAndOrPanic(w, errInsert, http.StatusInternalServerError,
		"When trying to write the data on the store a mistake has occurred",
		es.DoPanic)

	log.Infof("Inserted data into node -> (ID: %v) | (Key name: %v) | (RevNbr: %v) -> for (Client: %v)",
		keyCtx.GetNodeID(), keyCtx.GetKeyStrName(), currentRevNbr, r.RemoteAddr)

	answer.SendSuccessJSONAdd(w, http.StatusCreated, currentRevNbr, "")
}
