package clt_client

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"lc/common/mqtt"
	"mime/multipart"
	"net/http"
	"path"
	"strconv"
	"time"
)

// PublishProgram 发布节目
func (c cltClient) PublishProgram(m mqtt.Message, baseurl string) {
	var pro ProgramInfo
	m.PayloadJSON(&pro)
	if pro.Type == "" || pro.Name == "" {
		return
	}
	//准备节目文件和vsn文件
	payload, writer, err := prepareFiles(pro)
	defer writer.Close()
	if err != nil {
		return
	}
	req, _ := http.NewRequest("POST", baseurl+"program/"+pro.Name+".vsn", payload)
	req.Header.Add("Content-Type", "multipart/form-data")
	req.Header.Set("Content-Type", writer.FormDataContentType())
DoReq:
	n := 0
	resp, err := c.HttpClient.Do(req)
	defer resp.Body.Close()
	ioutil.ReadAll(resp.Body)
	if err != nil && n < 3 {
		n++
		time.Sleep(1500 * time.Millisecond)
		goto DoReq
	}
}

// 准备文件
func prepareFiles(pro ProgramInfo) (*bytes.Buffer, *multipart.Writer, error) {
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	defer writer.Close()
	for i, v := range pro.ImageInfo.Urls {
		//下载资源文件
		resp, err := http.Get(v)
		defer resp.Body.Close()

		if err != nil {
			return nil, nil, err
		}
		//准备资源文件
		part, err := writer.CreateFormFile(pro.Name+strconv.Itoa(i), path.Base(v))
		if err != nil {
			return nil, nil, err
		}
		_, err = io.Copy(part, resp.Body)
		if err != nil {
			return nil, nil, err
		}
	}
	//准备vsn文件
	pVsn := NewPVsn(pro)
	if pVsn == nil {
		return nil, nil, errors.New("发布节目准备文件出错!")
	}
	part0, _ := writer.CreateFormFile(pro.Name+"-vsn", pro.Name+".vsn")
	_, errFile3 := io.Copy(part0, bytes.NewReader(pVsn))
	if errFile3 != nil {
		return nil, nil, errFile3
	}
	return payload, writer, nil
}

func (c cltClient) CommonPost(payload []byte, url string) {
	var r io.Reader
	if payload == nil {
		return
	} else {
		r = bytes.NewReader(payload)
	}
	req, _ := http.NewRequest("POST", url, r)
	c.HttpClient.Do(req)
	return
}
