/**************************************************************************************
 *
 *     Project:    General use
 *     File name:  functionChainBuilder.go
 *     Version:    1.0.0
 *     Date:       2017-08-20
 *
 *     Autor:      Bogdanovic Theodor
 *     Contact:    t.bogdanovic@hotmail.com
 *
 *     License:    GPLv3
 *
 **************************************************************************************/
/**************************************************************************************
 * Copyright 2018 Bogdanovic Theodor
 *
 * This file is part of functionChainBuilder.
 *
 * functionChainBuilder 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.
 *
 * functionChainBuilder 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 functionChainBuilder.  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 functionChainBuilder ...
*/
package functionChainBuilder

import (
	"net/http"
)

//*****************************************************************************
//*
//*      Declarations
//*
//*****************************************************************************

// First-Class-Function definitions
// Here they serve as aliases to keep the signatures of methods / functions in
// the code small
type middlewareFuncAlias func(nextFunction http.Handler) http.Handler
type finalHandlerAlias func(w http.ResponseWriter, r *http.Request)

//*****************************************************************************
//*
//*      Structure ChainContainer
//*
//*****************************************************************************

// ChainContainer includes the middleware funtions and the one
// FinalHandler. From the outside, several chains can be formed
type ChainContainer struct {
	middleware   []middlewareFuncAlias
	finalHandler finalHandlerAlias
}

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

// RegisterFunctions registered functions that correspond
// to the signature-type middlewareAlias
func (slf *ChainContainer) RegisterFunctions(mWareFuncs ...middlewareFuncAlias) *ChainContainer {

	slf.middleware = append(slf.middleware, mWareFuncs...)

	return slf
}

// SetFinalHandler registers the final handler, which
// must contain the central logic of the controller
func (slf *ChainContainer) SetFinalHandler(fHandler finalHandlerAlias) *ChainContainer {

	slf.finalHandler = fHandler

	return slf
}

// RunChain checks if a FinalHandler is set and starts
// the function chain of the defined series.
// If no middleware functions have been defined, the
// final handler will always be executed
func (slf *ChainContainer) RunChain() http.Handler {

	if slf.finalHandler == nil {
		panic("Missing Final Handler in Function Chain!")
	}
	if slf.middleware != nil {
		return buildMiddlewareChain(&slf.finalHandler, slf.middleware)
	}
	return http.HandlerFunc(slf.finalHandler)
}

//*****************************************************************************
//*
//*      Public Function
//*
//*****************************************************************************

// NewChainConatainer creates a new empty structure from type
// ChainContainer and return it to the caller
func NewChainConatainer() *ChainContainer {

	var cContainer ChainContainer
	return &cContainer
}

//*****************************************************************************
//*
//*      Private Functions
//*
//*****************************************************************************

// buildMiddlewareChain is based on the standard pattern of go http middleware.
func buildMiddlewareChain(fHandler *finalHandlerAlias, mWareFuncs []middlewareFuncAlias) http.Handler {

	if len(mWareFuncs) == 0 {
		return http.HandlerFunc(*fHandler)
	}
	// Unlike the original, this function uses a simple incremental process
	// in the recursive call (see below). This always starts at 1 (not 0). 0 is
	// the original caller for the following recursive call. 1 is the new
	// function form Middleware slice.
	// Go modifies the static array under the slice for every call that does not
	// start from the beginning (ie 0). It cuts off the beginning to the defined
	// value and forms below a new array starting from 0 (in the slice the place
	// from where you started counting)
	return mWareFuncs[0](buildMiddlewareChain(fHandler, mWareFuncs[1:]))
}
