/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  delFinalHandler.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"
	"fmt"
	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"
)

//*****************************************************************************
//*
//*      Structure: deleteConfirm
//*
//*****************************************************************************

// deleteConfirm ...
type deleteConfirm struct {
	KeyName       string `json:"key_name"`
	ConfirmDelete bool   `json:"confirm_delete"`
}

//******************** Methods ************************************************

func (slf *deleteConfirm) notEqualTo(s string) bool { return slf.KeyName != s }

func (slf *deleteConfirm) notConfirmed() bool { return slf.ConfirmDelete != true }

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

// DelFinalHandler deletes the content of a node and its data stored at
// harddisk
//
// The logic is equivalent to the use -loeschen-
func DelFinalHandler(w http.ResponseWriter, r *http.Request) {

	defer eh.Try("FinalHandler->DelFinalHandler()")
	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.StatusInternalServerError,
		"Error by Key to=> ID mapping - Maybe forget the name?", es.DoPanic)

	newDelConfirm := deleteConfirm{}

	newJSONDecoder := json.NewDecoder(r.Body)

	errDecode := newJSONDecoder.Decode(&newDelConfirm)
	eh.IfErrBuildJSONAndOrPanic(w, errDecode, http.StatusInternalServerError,
		"Please check the syntax of your JSON document, there is an error",
		es.DoPanic)

	if newDelConfirm.notEqualTo(keyCtx.GetKeyStrName()) {
		eh.IfErrBuildJSONAndOrPanic(w,
			fmt.Errorf("Your URL key and the key name in the JSON are not equal | (URL)-> %v != (JSON)-> %v",
				keyCtx.GetKeyStrName(), newDelConfirm.KeyName),
			http.StatusBadRequest,
			"Your key name does not correspond to the name in URL", es.DoPanic)
	}
	if newDelConfirm.notConfirmed() {
		eh.IfErrBuildJSONAndOrPanic(w,
			fmt.Errorf("You forget to confirm the deletion | Recived-> (%v) || Wanted-> (true)",
				newDelConfirm.ConfirmDelete),
			http.StatusBadRequest,
			"You forgot to confirm the deletion", es.DoPanic)
	}

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

	delErr := bth.NewBtree().Del(keyCtx)
	eh.IfErrBuildJSONAndOrPanic(w, delErr, http.StatusInternalServerError,
		"Internal storage Error. Your key has not been deleted!", es.DoPanic)

	log.Infof("Successful delete node -> (ID: %v) | (Key name: %v) -> for (Client: %v)",
		keyCtx.GetNodeID(), keyCtx.GetKeyStrName(), r.RemoteAddr)

	answer.SendSuccessJSONDel(w, http.StatusOK, keyCtx.GetKeyStrName(),
		"All information was deleted")
}
