// Copyright 2021 Chaos Mesh Authors.
//
// 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 v1alpha1

import (
	"fmt"
	"reflect"
	"strconv"
	"time"

	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/util/validation/field"

	"github.com/chaos-mesh/chaos-mesh/api/genericwebhook"
)

const (
	// ValidateValueParseError defines the error message for value parse error
	ValidateValueParseError = "parse value field error:%s"
)

// FIXME: interface ContainsDuration only used for validating EmbedChaos in Workflow

// +kubebuilder:object:generate=false
type ContainsDuration interface {
	GetDuration() (*time.Duration, error)
}

type Duration string

func (d *Duration) Validate(root interface{}, path *field.Path) field.ErrorList {
	if d == nil {
		return nil
	}

	if len(*d) == 0 {
		// allow duration to be zero
		// TODO: control by tag
		return nil
	}

	_, err := time.ParseDuration(string(*d))
	if err != nil {
		return field.ErrorList{
			field.Invalid(path, d, fmt.Sprintf("parse duration field error: %s", err.Error())),
		}
	}

	return nil
}

func (d *Duration) Default(root interface{}, field *reflect.StructField) {
	if d == nil {
		return
	}

	// d cannot be nil
	if len(*d) == 0 && field != nil {
		*d = Duration(field.Tag.Get("default"))
	}
}

func (p *PodSelector) Validate(root interface{}, path *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	if p == nil {
		return nil
	}

	mode := p.Mode
	value := p.Value
	valueField := path.Child("value")

	switch mode {
	case FixedMode:
		num, err := strconv.Atoi(value)
		if err != nil {
			allErrs = append(allErrs, field.Invalid(valueField, value,
				fmt.Sprintf(ValidateValueParseError, err)))
			break
		}

		if num <= 0 {
			allErrs = append(allErrs, field.Invalid(valueField, value,
				fmt.Sprintf("value must be greater than 0 with mode:%s", FixedMode)))
		}

	case RandomMaxPercentMode, FixedPercentMode:
		percentage, err := strconv.Atoi(value)
		if err != nil {
			allErrs = append(allErrs, field.Invalid(valueField, value,
				fmt.Sprintf(ValidateValueParseError, err)))
			break
		}

		if percentage <= 0 || percentage > 100 {
			allErrs = append(allErrs, field.Invalid(valueField, value,
				fmt.Sprintf("value of %d is invalid, Must be (0,100] with mode:%s",
					percentage, mode)))
		}
	}

	return allErrs
}

func (p *PodSelector) Default(root interface{}, field *reflect.StructField) {
	if p == nil {
		return
	}

	metaData, err := meta.Accessor(root)
	if err != nil {
		return
	}

	if len(p.Selector.Namespaces) == 0 {
		p.Selector.Namespaces = []string{metaData.GetNamespace()}
	}
}

type Percent int

type FloatStr string

func (p *Percent) Validate(root interface{}, path *field.Path) field.ErrorList {
	if p == nil {
		return nil
	}

	allErrs := field.ErrorList{}

	if *p > 100 || *p < 0 {
		allErrs = append(allErrs, field.Invalid(path, p,
			"percent field should be in 0-100"))
	}

	return allErrs
}

func (f *FloatStr) Validate(root interface{}, path *field.Path) field.ErrorList {
	if f == nil {
		return nil
	}

	_, err := strconv.ParseFloat(string(*f), 32)
	if err != nil {
		return field.ErrorList{
			field.Invalid(path, f,
				fmt.Sprintf("parse correlation field error:%s", err.Error())),
		}
	}

	return nil
}

func (f *FloatStr) Default(root interface{}, field *reflect.StructField) {
	// f cannot be nil
	if len(*f) == 0 && field != nil {
		*f = FloatStr(field.Tag.Get("default"))
	}
}

func init() {
	genericwebhook.Register("Duration", reflect.PtrTo(reflect.TypeOf(Duration(""))))
	genericwebhook.Register("Percent", reflect.PtrTo(reflect.TypeOf(Percent(0))))
	genericwebhook.Register("FloatStr", reflect.PtrTo(reflect.TypeOf(FloatStr(""))))
}
