package eapi

import (
	"bytes"
	"encoding/json"
	"io"
)

// Unmarshal 转换json
func Unmarshal(body io.ReadCloser, v interface{}) (err error) {
	b, err := copyBody(body)
	if err != nil {
		return
	}

	out := new(bytes.Buffer)
	if _, err = out.ReadFrom(b); err != nil {
		return
	}

	if err = json.Unmarshal(out.Bytes(), &v); err != nil {
		return
	}

	return
}

// String 转换为字串符
func String(body io.ReadCloser) (string, error) {
	b, err := copyBody(body)
	if err != nil {
		return "", err
	}

	out := new(bytes.Buffer)
	if _, err = out.ReadFrom(b); err != nil {
		return "", err
	}

	return out.String(), nil
}

// Bytes 转换为Bytes
func Bytes(body io.ReadCloser) ([]byte, error) {
	b, err := copyBody(body)
	if err != nil {
		return nil, err
	}

	out := new(bytes.Buffer)
	if _, err = out.ReadFrom(b); err != nil {
		return nil, err
	}

	return out.Bytes(), nil
}

func copyBody(body io.ReadCloser) (*bytes.Buffer, error) {
	var (
		b1 = bytes.NewBuffer([]byte{})
		b2 = bytes.NewBuffer([]byte{})
		tr io.Reader
	)

	if body != nil {
		tr = io.TeeReader(body, b1)
		defer body.Close()

		if _, err := io.Copy(b2, tr); err != nil {
			return nil, err
		}

		defer func() { body = io.NopCloser(b1) }()
	}

	return b2, nil
}
