/**
= Creative Commons Lizenzvertrag =
Diese Software ist von der archium GmbH, Gera ist lizenziert unter einer Creative Commons Namensnennung - Nicht kommerziell - Keine Bearbeitungen 4.0 International Lizenz. (http://creativecommons.org/licenses/by-nc-nd/4.0/deed.de)
Individuelle über diese Lizenz hinausgehende Berechtigungen können Sie unter https://archium.org erhalten.

= Creative Commons License =
Software by archium GmbH, Gera is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. (http://creativecommons.org/licenses/by-nc-nd/4.0/)
Individual permissions beyond the scope of this license may be available at https://archium.org.
**/

package defaults

import (
	// "errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"

	// "time"
	//
	gjs "github.com/tidwall/gjson"
)

// DEF_log == 0	-> log aus
const DEF_lognone = 0                                          // -> log aus
const DEF_logerro = 1                                          // -> log an + fehler
const DEF_logwarn = 2                                          // -> log an + warnungen
const DEF_loginfo = 3                                          // -> log an + nachrichten
const DEF_logdebg = 4                                          // -> log an + alles
var DEF_log int = DEF_logerro                                  // >0 = log an
var DEF_alias string = ":root"                                 // start.alias
var DEF_apikey string = "00000000-0000-0000-0000-000000000000" // start.apikey
var DEF_siteurl string = "http://127.0.0.1:8080"               // start.siteurl
var DEF_routeurl string = "https://planetary-data-portal.org"  // start.routeurl
var DEF_idletime float64 = 1800                                // start.release (sekunden)
var DEF_codebase string = "static"                             // root für verzeichnisse
var DEF_toolboxdirs string = ";/fubagDataset;"                 //
var DEF_metrixdirs string = "/fubagMetrix"                     // replacement for former metrixToolbox
var DEF_wasmdirs_www string = "/wasm/"
var DEF_wasmdirs_fs string = "static/wasm"

var DEF_httphost string = "127.0.0.1"
var DEF_httpport int = 8085
var DEF_dbhost string = "127.0.0.1"
var DEF_dbport int = 6414
var DEF_dbuser string = "postgres"
var DEF_dbpassword string = "postgres"
var DEF_dbname string = "fubagTools"

const DEF_dateISO = "2006-01-02"
const DEF_timeISO = "15:04:05"
const DEF_stampISO = "2006-01-02 15:04:05"

const (
	DEF_customerid    = 1
	DEF_project       = "archium"
	DEF_coninfo       = "sslmode=disable host=%s port=%d user=%s password=%s dbname=%s sslmode=disable"
	DEF_schema        = "html"
	DEF_tablecustomer = "html_customer"
	DEF_tablelayout   = "html_layout"
	DEF_tablecontent  = "html_content"
	DEF_fieldsiteurl  = "hla_siteurl"
	DEF_fieldrouteurl = "hla_routeurl"
	DEF_fieldlayout   = "hla_layout"
	DEF_fieldsource   = "hla_source"
	DEF_fieldcontent  = "hco_content"
	DEF_fieldalias    = "hcu_aliasroot"
	DEF_fieldapikey   = "hcu_apikey"
	DEF_fieldidletime = "hcu_idleseconds"
	DEF_fieldproject  = "hcu_project"
	DEF_sqllayout     = "SELECT hcu.*, hla.* " +
		"FROM %schema%.%tablecustomer% hcu " +
		"LEFT JOIN %schema%.%tablelayout% hla ON hla.hla_customerid = hcu.hcu_customerid " +
		"WHERE hcu.hcu_customerid = %customerid%;"
	DEF_sqlcontent = "SELECT hcu.*, hla.*, hco.* " +
		"FROM %schema%.%tablecustomer% hcu " +
		"LEFT JOIN %schema%.%tablelayout% hla ON hla.hla_customerid = hcu.hcu_customerid " +
		"LEFT JOIN %schema%.%tablecontent% hco ON hco.hco_customerid = hcu.hcu_customerid " +
		"WHERE hcu.hcu_customerid = %customerid% AND hco.hco_type = '%type%' " +
		"ORDER BY hco_layoutid ASC, hco_contentid ASC;"
	DEF_sqlproject = "SELECT hcu.* " +
		"FROM %schema%.%tablecustomer% hcu " +
		"WHERE hcu.hcu_customerid = %customerid%;"
	DEF_sqlgetjson = "SELECT html.\"GetJson\";('%json%');"
	DEF_sqlgetsvg  = "SELECT * FROM html.\"GetSvg\"(%shadow%,%width%,%height%,'%matrix%','%viewbox%','%names%');"
	//
	DEF_sqlUserParam = "id,userIdentifier,lastName,firstName"
	DEF_sqlUserAdd   = "SELECT html.\"AddUser\"('%id%', '%userIdentifier%', '%lastName%', '%firstName%');"
)

func MenuRoot(_alias, _name string) string {
	return "{\n" + //
		"\t&#34;success&#34;: true,\n" + //
		"\t&#34;rows&#34;:[{\n" + //
		"\t\t&#34;id&#34;:1,\n" + //
		"\t\t&#34;text&#34;:&#34;" + _name + "&#34;,\n" + // start-dataverse
		"\t\t&#34;iconCls&#34;:&#34;icon-package&#34;,\n" +
		"\t\t&#34;attributes&#34;:{&#34;level&#34;:1,&#34;alias&#34;:&#34;" + _alias + "&#34;,&#34;name&#34;:&#34;" + _name + "&#34;,&#34;datasetPid&#34;:&#34;%datasetPid%&#34;},\n" + //
		"\t\t&#34;children&#34;:%children%\n" + //
		"\t}]\n" + //
		"}"
}

func MenuChildDataverse() string {
	return "{\n" + //
		"%tabb%&#34;id&#34;:%id%,\n" + //
		"%tabb%&#34;text&#34;:&#34;%count%%title%&#34;,\n" + //
		"%icon%" + //
		"%tabb%&#34;attributes&#34;:{&#34;level&#34;:%level%,&#34;type&#34;:&#34;%type%&#34;," + //
		"&#34;title&#34;:&#34;%title%&#34;,&#34;alias&#34;:&#34;%alias%&#34;,&#34;name&#34;:&#34;%name%&#34;},\n" + //
		"%tabb%&#34;children&#34;:%children%\n" + //
		"%taba%}"
}

func MenuChildDataset() string {
	return "{\n" +
		"%tabb%&#34;id&#34;:%id%,\n" + //
		"%tabb%&#34;text&#34;:&#34;%count%%title%&#34;,\n" + //
		"%icon%" + //
		"%tabb%&#34;attributes&#34;:{&#34;level&#34;:%level%,&#34;type&#34;:&#34;%type%&#34;," + //
		"&#34;datasetPid&#34;:&#34;%datasetPid%&#34;,&#34;datasetId&#34;:&#34;%datasetId%&#34;," + //
		"&#34;title&#34;:&#34;%title%&#34;,&#34;subject&#34;:%subjects%},\n" + //
		"%tabb%&#34;children&#34;:%children%\n" + //
		"%taba%}"
}

func MenuChildFile() string {
	return "{\n" + //
		"%tabb%&#34;id&#34;:%id%,\n" + //
		"%tabb%&#34;text&#34;:&#34;%label%&#34;,\n" + //
		"%icon%" + //
		"%tabb%&#34;attributes&#34;:{&#34;level&#34;:%level%,&#34;type&#34;:&#34;%type%&#34;},\n" + //
		"%tabb%&#34;children&#34;:[]\n" + //
		"%taba%}"
}

func MenuChildFileSimple() string {
	return "{\n" + //
		"%tabb%&#34;text&#34;:&#34;%label%&#34;,\n" + //
		"%icon%" + //
		"%tabb%&#34;attributes&#34;:{&#34;level&#34;:%level%,&#34;type&#34;:&#34;%type%&#34;},\n" + //
		"%tabb%&#34;children&#34;:[]\n" + //
		"%taba%}"
}

func MenuChildUser() string {
	return "{\n" +
		"\t&#34;id&#34;:%id%,\n" +
		"\t&#34;text&#34;:&#34;%name%&#34;,\n" +
		"\t&#34;attributes&#34;:{&#34;level&#34;:%level%,&#34;lastname&#34;:&#34;%lastname%&#34;,&#34;firstname&#34;:&#34;%firstname%&#34;}\n" +
		"}"
}

func LogToggle(_logging int) int {
	oldlog := DEF_log
	//
	if _logging != 0 {
		log.SetOutput(os.Stdout)
	} else {
		log.SetOutput(ioutil.Discard)
	}
	DEF_log = _logging
	//
	return oldlog
}

func LogMessage(_label, _message string, _loglevel int) {
	if _loglevel > 0 {
		if _loglevel <= DEF_log {
			// DEF_log == 1	-> log an + fehler
			// DEF_log == 2	-> log an + warnungen
			// DEF_log == 3	-> log an + nachrichten
			// DEF_log == 4	-> log an + mimimi
			if len(_label) > 0 {
				switch _loglevel {
				case 1:
					log.Printf("( ERROR ) > %v: %v \n", _label, _message)
				case 2:
					log.Printf("( WARN  ) > %v: %v \n", _label, _message)
				case 3:
					log.Printf("( INFO  ) > %v: %v \n", _label, _message)
				case 4:
					log.Printf("( DEBG  ) > %v: %v \n", _label, _message)
				}
			} else {
				switch _loglevel {
				case 1:
					log.Printf("( ERROR ) > %v \n", _message)
				case 2:
					log.Printf("( WARN  ) > %v \n", _message)
				case 3:
					log.Printf("( INFO  ) > %v \n", _message)
				case 4:
					log.Printf("( DEBG  ) > %v \n", _message)
				}
			}
		}
	}
}

func LogMessage2Level(_label, _message string, _loglevel int) {
	oldlog := LogToggle(_loglevel)
	LogMessage(_label, _message, _loglevel)
	LogToggle(oldlog)
}

func LogError(_label string, _error error) {
	oldlog := LogToggle(1)
	LogMessage(_label, fmt.Sprintf("%v", _error), DEF_logerro)
	LogToggle(oldlog)
}

func GetArguments() {
	allArgs := os.Args[1:]
	if len(allArgs) > 0 {
		log.Println("Initialize package - Parameter..")
		//LogToggle(1)
		for i, vparam := range allArgs {
			mparam := strings.Split(vparam, ":")
			switch mparam[0] {
			case "log":
				iint, err := strconv.Atoi(mparam[1])
				if err == nil {
					LogToggle(1)
					log.Printf("\t[%v]: '%v:%v'\n", i, mparam[0], mparam[1])
					LogToggle(iint)
					continue
				}
			case "host":
				DEF_httphost = mparam[1]
			case "port":
				iint, err := strconv.Atoi(mparam[1])
				if err == nil {
					DEF_httpport = iint
				}
			case "codebase":
				DEF_codebase = mparam[1]
			case "toolboxdirs":
				DEF_toolboxdirs = mparam[1]
			case "metrixdirs":
				DEF_metrixdirs = mparam[1]
			case "dbpassword":
				DEF_dbpassword = mparam[1]
			case "dbuser":
				DEF_dbuser = mparam[1]
			case "dbname":
				DEF_dbname = mparam[1]
			case "dbhost":
				DEF_dbhost = mparam[1]
			case "dbport":
				iint, err := strconv.Atoi(mparam[1])
				if err == nil {
					DEF_dbport = iint
				}
			case "dataverse":
				DEF_alias = mparam[1]
			default:
				oldlog := LogToggle(DEF_logerro)
				LogMessage("GetArguments()", fmt.Sprintf("\t[%v]: '%v:%v' is unknown.\n", i, mparam[0], mparam[1]), DEF_logerro)
				LogToggle(oldlog)
				continue
			}
			//log.Printf("\t[%v]: '%v:%v'\n", i, mparam[0], mparam[1])
		}
	}
}

// fehler bereitstellen (momentan 20210316)
func get_error(_error string, _type string) string {
	json := "\t" + `"success":false,` + "\n"
	json = json + "\t" + `"msg":` + "{\n"
	status := gjs.Get(_error, "status")
	if status.String() == "ERROR" {
		message := gjs.Get(_error, "message")
		if len(message.String()) > 0 {
			json = json + "\t\t" + `"title"` + ":" + `"Error"` + ",\n"
			json = json + "\t\t" + `"msg"` + ":" + `"%message%"` + ",\n"
			json = json + "\t\t" + `"type"` + ":" + `"%type%"`
			json = strings.Replace(json, "%message%", strings.Replace(message.String(), "&#34;", "'", -1), -1)
			json = strings.Replace(json, "%type%", _type, -1)
		}
	} else {
		if status.Type == gjs.Null {
			message := fmt.Sprintf("%v", _error)
			if len(message) > 0 {
				json = json + "\t\t" + `"title"` + ":" + `"Error"` + ",\n"
				json = json + "\t\t" + `"msg"` + ":" + `"%message%"` + ",\n"
				json = json + "\t\t" + `"type"` + ":" + `"%type%"`
				json = strings.Replace(json, "%message%", strings.Replace(message, "&#34;", "'", -1), -1)
				json = strings.Replace(json, "%type%", _type, -1)
			}
		}
	}
	json = json + "\n\t}"
	//
	return json
}

func GetError(_error error, _type, _label string) string {
	//
	sjson := "{\n" + get_error(fmt.Sprintf("%v:<BR><BR> %v", _label, _error), _type) + "\n}"
	//
	return sjson
}

func GetErrorByString(_error, _type, _label string) string {
	//
	sjson := get_error(fmt.Sprintf("%v:<BR><BR> %v", _label, _error), _type)
	//
	return sjson
}
