/*
Copyright © 2021 da/net Research Group <danet@h-da.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package cmd

import (
	"context"
	"errors"
	"fmt"
	"net"
	"strconv"

	gpb "github.com/openconfig/gnmi/proto/gnmi"
	gnmiv "github.com/openconfig/gnmi/value"
	"github.com/openconfig/goyang/pkg/yang"
	"google.golang.org/grpc/metadata"
)

func checkIPPort(string) error {
	// check if address is in the format <IP>:<port>
	ip, _, err := net.SplitHostPort(address)
	if err != nil {
		return err
	}
	// Check IP
	ip2 := net.ParseIP(ip)
	if ip2 == nil {
		return errors.New("invalid IP")
	}
	return nil
}

// sliceContains checks if a slice contains the given item.
func sliceContains[T comparable](slice []T, toCompare T) bool {
	for _, sliceEntry := range slice {
		if sliceEntry == toCompare {
			return true
		}
	}
	return false
}

func createContextWithAuthorization() context.Context {
	//TODO: try to get token string first, if "" return err, followed by print in cli about required login
	md := metadata.Pairs("authorize", userToken)
	return metadata.NewOutgoingContext(context.Background(), md)
}

// convertStringToGnmiTypedValue allows to convert a string into a
// gnmi.TypedValue; this conversion is based on the provided YANG type.
func convertStringToGnmiTypedValue(s string, t *yang.YangType) (*gpb.TypedValue, error) {
	// TODO: add more types
	switch t.Kind {
	case yang.Yint8, yang.Yint16, yang.Yint32, yang.Yint64:
		return convertStringToIntTypedValue(s)
	case yang.Yuint8, yang.Yuint16, yang.Yuint32, yang.Yuint64:
		return convertStringToUintTypedValue(s)
	case yang.Ybool:
		parsedBool, err := strconv.ParseBool(s)
		if err != nil {
			return nil, err
		}
		return gnmiv.FromScalar(parsedBool)
	case yang.Ystring:
		return gnmiv.FromScalar(s)
	default:
		return nil, fmt.Errorf("could not convert to TypedValue, unsupported type of: %v", t)
	}
}

func convertStringToIntTypedValue(s string) (*gpb.TypedValue, error) {
	parsedInt, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return nil, err
	}
	return &gpb.TypedValue{
		Value: &gpb.TypedValue_IntVal{
			IntVal: int64(parsedInt),
		},
	}, nil
}

func convertStringToUintTypedValue(s string) (*gpb.TypedValue, error) {
	parsedInt, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		return nil, err
	}
	return &gpb.TypedValue{
		Value: &gpb.TypedValue_UintVal{
			UintVal: uint64(parsedInt),
		},
	}, nil
}
