package arg

import (
	
	
	

	scalar 
)

// setSliceOrMap parses a sequence of strings into a slice or map. If clear is
// true then any values already in the slice or map are first removed.
func setSliceOrMap( reflect.Value,  []string,  bool) error {
	if !.CanSet() {
		return fmt.Errorf("field is not writable")
	}

	 := .Type()
	if .Kind() == reflect.Ptr {
		 = .Elem()
		 = .Elem()
	}

	switch .Kind() {
	case reflect.Slice:
		return setSlice(, , )
	case reflect.Map:
		return setMap(, , )
	default:
		return fmt.Errorf("setSliceOrMap cannot insert values into a %v", )
	}
}

// setSlice parses a sequence of strings and inserts them into a slice. If clear
// is true then any values already in the slice are removed.
func setSlice( reflect.Value,  []string,  bool) error {
	var  bool
	 := .Type().Elem()
	if .Kind() == reflect.Ptr && !.Implements(textUnmarshalerType) {
		 = true
		 = .Elem()
	}

	// clear the slice in case default values exist
	if  && !.IsNil() {
		.SetLen(0)
	}

	// parse the values one-by-one
	for ,  := range  {
		 := reflect.New()
		if  := scalar.ParseValue(.Elem(), );  != nil {
			return 
		}
		if ! {
			 = .Elem()
		}
		.Set(reflect.Append(, ))
	}
	return nil
}

// setMap parses a sequence of name=value strings and inserts them into a map.
// If clear is true then any values already in the map are removed.
func setMap( reflect.Value,  []string,  bool) error {
	// determine the key and value type
	var  bool
	 := .Type().Key()
	if .Kind() == reflect.Ptr && !.Implements(textUnmarshalerType) {
		 = true
		 = .Elem()
	}

	var  bool
	 := .Type().Elem()
	if .Kind() == reflect.Ptr && !.Implements(textUnmarshalerType) {
		 = true
		 = .Elem()
	}

	// clear the slice in case default values exist
	if  && !.IsNil() {
		for ,  := range .MapKeys() {
			.SetMapIndex(, reflect.Value{})
		}
	}

	// allocate the map if it is not allocated
	if .IsNil() {
		.Set(reflect.MakeMap(.Type()))
	}

	// parse the values one-by-one
	for ,  := range  {
		// split at the first equals sign
		 := strings.Index(, "=")
		if  == -1 {
			return fmt.Errorf("cannot parse %q into a map, expected format key=value", )
		}

		// parse the key
		 := reflect.New()
		if  := scalar.ParseValue(.Elem(), [:]);  != nil {
			return 
		}
		if ! {
			 = .Elem()
		}

		// parse the value
		 := reflect.New()
		if  := scalar.ParseValue(.Elem(), [+1:]);  != nil {
			return 
		}
		if ! {
			 = .Elem()
		}

		// add it to the map
		.SetMapIndex(, )
	}
	return nil
}