package nkeys

import (
	
	
	
)

var userConfigRE = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}\r?\n))`)

// ParseDecoratedJWT takes a creds file and returns the JWT portion.
func ( []byte) (string, error) {
	 := userConfigRE.FindAllSubmatch(, -1)
	if len() == 0 {
		return string(), nil
	}
	// First result should be the user JWT.
	// We copy here so that if the file contained a seed file too we wipe appropriately.
	 := [0][1]
	 := make([]byte, len())
	copy(, )
	return strings.TrimSpace(string()), nil
}

// ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a
// key pair from it.
func ( []byte) (KeyPair, error) {
	var  []byte

	 := userConfigRE.FindAllSubmatch(, -1)
	if len() > 1 {
		 = [1][1]
	} else {
		 := bytes.Split(, []byte("\n"))
		for ,  := range  {
			if bytes.HasPrefix(bytes.TrimSpace(), []byte("SO")) ||
				bytes.HasPrefix(bytes.TrimSpace(), []byte("SA")) ||
				bytes.HasPrefix(bytes.TrimSpace(), []byte("SU")) {
				 = 
				break
			}
		}
	}
	if  == nil {
		return nil, ErrNoSeedFound
	}
	if !bytes.HasPrefix(, []byte("SO")) &&
		!bytes.HasPrefix(, []byte("SA")) &&
		!bytes.HasPrefix(, []byte("SU")) {
		return nil, ErrInvalidNkeySeed
	}
	,  := FromSeed()
	if  != nil {
		return nil, 
	}
	return , nil
}

// ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a
// key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys.
func ( []byte) (KeyPair, error) {
	,  := ParseDecoratedNKey()
	if  != nil {
		return nil, 
	}
	,  := .Seed()
	if  != nil {
		return nil, 
	}
	if !bytes.HasPrefix(, []byte("SU")) {
		return nil, ErrInvalidUserSeed
	}
	,  := FromSeed()
	if  != nil {
		return nil, 
	}
	return , nil
}