package conv

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"gadmin/utility"
	"github.com/nahid/gohttp"
	"github.com/sirupsen/logrus"
	"io"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func GetUrlBody(version string, fileName string) ([]byte, error) {
	url := utility.PullJsonAddr(version, fileName)
	logrus.Info("GetUrlBody url:", url)
	tr := &http.Transport{
		TLSClientConfig:    &tls.Config{InsecureSkipVerify: true},
		DisableCompression: true,
		Dial: func(netw, addr string) (net.Conn, error) {
			deadline := time.Now().Add(15 * time.Second)
			c, err := net.DialTimeout(netw, addr, time.Second*3)
			if err != nil {
				return nil, err
			}
			c.SetDeadline(deadline)
			return c, nil
		},
	}
	a1 := gohttp.SetTransport(tr)
	req := gohttp.NewRequest(a1)
	resp, err := req.Get(url)
	if err != nil {
		return nil, err
	}
	if resp.GetStatusCode() != 200 {
		return nil, errors.New(strconv.Itoa(resp.GetStatusCode()))
	}

	return resp.GetBodyAsByte()
}

func SaveJsonPath(filePath string, v interface{}) {
	logrus.Infoln("Create filePath:", filePath)
	index := strings.LastIndex(filePath, "/")
	if index == -1 {
		logrus.Errorln("文件路径错误！")
		return
	}

	utility.CreateDir(filePath[:index])

	ptrFile2, err := os.Create(filePath)
	if err != nil {
		logrus.Errorln("写日志文件失败", err)
	}
	defer ptrFile2.Close()
	encoder := json.NewEncoder(ptrFile2)
	if err = encoder.Encode(&v); err != nil {
		logrus.Infoln("Encoder failed", err.Error())
	} else {
		logrus.Infoln("Encoder success")
	}
}

func HttpRequestToFile(url string, dstFileName string) error {
	logrus.Infof("HttpRequestToFile url:%v ,dstFileName:%v", url, dstFileName)
	tr := &http.Transport{
		TLSClientConfig:    &tls.Config{InsecureSkipVerify: true},
		DisableCompression: true,
		Dial: func(netw, addr string) (net.Conn, error) {
			deadline := time.Now().Add(15 * time.Second)
			c, err := net.DialTimeout(netw, addr, time.Second*3)
			if err != nil {
				return nil, err
			}
			c.SetDeadline(deadline)
			return c, nil
		},
	}
	a1 := gohttp.SetTransport(tr)
	req := gohttp.NewRequest(a1)

	resp, err := req.Get(url)
	if err != nil {
		return err
	}
	if resp.GetStatusCode() != 200 {
		return errors.New(strconv.Itoa(resp.GetStatusCode()))
	}
	body := resp.GetBody()
	if body == nil {
		return nil
	}
	defer body.Close()

	dstFile, err := os.Create(dstFileName) //, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		return err
	}
	io.Copy(dstFile, body)

	return nil
}
