/**
 * Copyright (c) 2022 Yansen Zhang
 * wxcomponent is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
**/

package utils

import (
	"encoding/xml"
	"math/rand"
	"strings"
	"time"

	"gitee.com/yansen_zh/wxcomponent/utils/encrypt"
)

// RandStr 获取指定 n 长度的随机字符串
func RandStr(n int) string {
	arr := strings.Split("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "")
	arrLen := len(arr)
	seed := time.Now().Unix()

	r := rand.New(rand.NewSource(seed))
	dst := make([]string, n)

	for i := range dst {
		p := r.Intn(arrLen)
		dst[i] = arr[p]
	}

	return strings.Join(dst, "")
}

// GetExpireTime 获取过期时间
func GetExpireTime(sec int) time.Time {
	return time.Now().Add(time.Duration(sec) * time.Second)
}

// DeCodeXML 解析XML到MAP
func DeCodeXML(src []byte) (*encrypt.XMLMap, error) {
	dst := new(encrypt.XMLMap)

	err := xml.Unmarshal(src, dst)

	return dst, err
}