// Copyright 2016 IBM Corporation
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package config

import (
	"fmt"

	"errors"
	"net/url"

	"github.com/Sirupsen/logrus"
	"github.com/amalgam8/amalgam8/controller/util"
	"github.com/urfave/cli"
)

// Database types
const (
	DatabaseTypeRedis  = "redis"
	DatabaseTypeMemory = "memory"
	DatabaseTypeK8S    = "kubernetes"
)

// Database config
type Database struct {
	Type      string
	Username  string
	Password  string
	Host      string
	Namespace string
}

// Config for the controller
type Config struct {
	Database     Database
	APIPort      int
	SecretKey    string
	LogLevel     logrus.Level
	AuthModes    []string
	JWTSecret    string
	RequireHTTPS bool
}

// New config instance
func New(context *cli.Context) *Config {
	// TODO: parse this more gracefully
	loggingLevel := logrus.DebugLevel
	logLevelArg := context.String(logLevelFlag)
	var err error
	loggingLevel, err = logrus.ParseLevel(logLevelArg)
	if err != nil {
		loggingLevel = logrus.DebugLevel
	}

	return &Config{
		Database: Database{
			Type:      context.String(dbTypeFlag),
			Username:  context.String(dbUserFlag),
			Password:  context.String(dbPasswordFlag),
			Host:      context.String(dbHostFlag),
			Namespace: context.String(dbNamespace),
		},
		APIPort:      context.Int(apiPortFlag),
		SecretKey:    context.String(secretKeyFlag),
		LogLevel:     loggingLevel,
		AuthModes:    context.StringSlice(authModeFlag),
		JWTSecret:    context.String(jwtSecretFlag),
		RequireHTTPS: context.Bool(requireHTTPSFlag),
	}
}

// Validate the config
func (c *Config) Validate() error {
	// Create list of validation checks
	validators := []util.ValidatorFunc{
		util.IsNotEmpty("Database type", c.Database.Type),
		util.IsInRange("API port", c.APIPort, 1, 65535),
		util.IsNotEmpty("Secret key", c.SecretKey),
	}

	switch c.Database.Type {
	case DatabaseTypeRedis:
		validators = append(
			validators,
			func() error {
				u, err := url.Parse(c.Database.Host)
				if err != nil {
					return errors.New("Redis database host name is not a valid URL")
				}

				if u.Scheme != "redis" {
					return errors.New("Redis database host name must have scheme of 'redis'")
				}

				return nil
			},
		)
	case DatabaseTypeK8S:
		validators = append(validators,
			util.IsNotEmpty("Database namespace", c.Database.Namespace),
		)
	case DatabaseTypeMemory:
	default:
		return fmt.Errorf("Invalid database type %v", c.Database.Type)
	}

	if len(c.SecretKey) != 16 {
		return fmt.Errorf("Secret must have a length of 16 characters")
	}

	return util.Validate(validators)
}
