/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  testCaseRef_4_3_006_test.go
 *     Version:    1.0.0
 *     Date:       2018-01-13
 *
 *     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 main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
)

// Test4_3_006_test adds an entry to the kvmstoreserver and deletes it again.
// This process is repeated three times. At each repetition it is checked if a
// positive status code (200) comes back and if the deletion text is contained
// (All information was deleted)
func Test4_3_006_test(t *testing.T) {

	// Create test struct for the test data
	type innerStruct []struct {
		name      string
		keySeqNbr int
		revNbr    int
		cliAction clientAction
		httpMeth  string
	}

	// Create test data
	insertValues := map[int]innerStruct{}
	insertValues = make(map[int]innerStruct, 0)
	insertValues[0] = innerStruct{
		// Test sequence 1
		{name: "Test 1_1: Try to insert entry first time (Controller /add/ | Method POST)", keySeqNbr: 700, revNbr: 0, cliAction: actionAdd, httpMeth: POST},
		{name: "Test 1_2: Try to delete entry (Controller /del/ | Method DELETE)", keySeqNbr: 700, revNbr: 0, cliAction: actionDel, httpMeth: DELETE},
	}
	insertValues[1] = innerStruct{
		// Test sequence 2
		{name: "Test 2_1: Try to insert entry first time (Controller /add/ | Method POST)", keySeqNbr: 701, revNbr: 0, cliAction: actionAdd, httpMeth: POST},
		{name: "Test 2_2: Try to delete entry (Controller /del/ | Method DELETE)", keySeqNbr: 701, revNbr: 0, cliAction: actionDel, httpMeth: DELETE},
	}
	insertValues[2] = innerStruct{
		// Test sequence 3
		{name: "Test 3_1: Try to insert entry first time (Controller /add/ | Method POST)", keySeqNbr: 702, revNbr: 0, cliAction: actionAdd, httpMeth: POST},
		{name: "Test 3_2: Try to delete entry (Controller /del/ | Method DELETE)", keySeqNbr: 702, revNbr: 0, cliAction: actionDel, httpMeth: DELETE},
	}

	// Create test data (delete instructions)
	deleteValues := map[int]innerStruct{}
	deleteValues = make(map[int]innerStruct, 0)
	deleteValues[0] = innerStruct{
		// Delete instuctions for all keys
		{name: "Test 1_3: Try to delete entry (Controller /get/ | Method GET)", keySeqNbr: 700, revNbr: 0, cliAction: actionGet, httpMeth: GET},
		{name: "Test 2_3: Try to delete entry (Controller /get/ | Method GET)", keySeqNbr: 701, revNbr: 0, cliAction: actionGet, httpMeth: GET},
		{name: "Test 3_3: Try to delete entry (Controller /get/ | Method GET)", keySeqNbr: 702, revNbr: 0, cliAction: actionGet, httpMeth: GET},
	}

	// Start a test server in a separate gourutine
	runKvmssTestInstance()

	// Clean up the environment (if there are remnants of the last test)
	testClient(insertValues[0][0].keySeqNbr, insertValues[0][0].revNbr, actionDel, DELETE, "")
	testClient(insertValues[1][0].keySeqNbr, insertValues[1][0].revNbr, actionDel, DELETE, "")
	testClient(insertValues[2][0].keySeqNbr, insertValues[2][0].revNbr, actionDel, DELETE, "")

	// Execute the test series
	for _, insertOuter := range insertValues {
		for _, insertInner := range insertOuter {
			t.Run(insertInner.name, func(t *testing.T) {
				testClient(insertInner.keySeqNbr, insertInner.revNbr, insertInner.cliAction, insertInner.httpMeth, "")
			})
		}
	}

	for _, outer := range deleteValues {
		for _, tt := range outer {
			got := testClient(tt.keySeqNbr, tt.revNbr, tt.cliAction, tt.httpMeth, "")
			if result, status, errMsg := parseBodyAfterDel(got); result {
				t.Errorf("Start testClient() (%v) = %v - %v, want %v - %v", tt, status, errMsg, 400, "The container with the name \"...\" existed once, but its contents were deleted")
			}
		}
	}

	// Post job: Clean up the environment
	testClient(insertValues[0][0].keySeqNbr, insertValues[0][0].revNbr, actionDel, DELETE, "")
	testClient(insertValues[1][0].keySeqNbr, insertValues[1][0].revNbr, actionDel, DELETE, "")
	testClient(insertValues[2][0].keySeqNbr, insertValues[2][0].revNbr, actionDel, DELETE, "")
}

// Here valid standard parser. Accepts the response of the testClient,
// decodes it and returns the following:
//
// @var bool   = If the JSON field NewRevisionNumber from response (StatusCode != 200) == false
// @var int	   = The status code from the current reponse
// @var string = The description JSON field of the current response
func parseBodyAfterDel(resp *http.Response) (bool, int, string) {

	innerStruct := struct {
		StatusCode           int    `json:"status_code"`
		Description          string `json:"description"`
		OriginalErrorMessage string `json:"original_error_message"`
	}{}

	body, errBody := ioutil.ReadAll(resp.Body)
	if errBody != nil {
		errMsg := fmt.Sprintf("Can not read body content (OrigErr)-> %v", errBody)
		panic(errMsg)
	}

	errJSON := json.Unmarshal(body, &innerStruct)
	if errJSON != nil {
		errMsg := fmt.Sprintf("Can not decode JSON from body (OrigErr)-> %v", errJSON)
		panic(errMsg)
	}

	if innerStruct.StatusCode != 400 ||
		!strings.Contains(innerStruct.OriginalErrorMessage, "existed once, but its contents were deleted") {
		return true, innerStruct.StatusCode, innerStruct.OriginalErrorMessage
	}

	return false, innerStruct.StatusCode, innerStruct.OriginalErrorMessage
}
