package http

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"netease_control_center/interfaces/log"
	"os"
)

func PostBackupFile(fileid string, filepath string) error {
	var b bytes.Buffer
	url := Url(URL_POST_FILE)
	w := multipart.NewWriter(&b)

	if fw, err := w.CreateFormField("vboxMac"); err == nil {
		fw.Write([]byte(fileid))
	} else {
		log.Println(log.ErrorLog, err)
	}

	if fw, err := w.CreateFormField("reqbase"); err == nil {
		if data, err := json.Marshal(Reqbase); err == nil {
			fw.Write(data)
		}
	} else {
		log.Println(log.ErrorLog, err)
	}

	if fw, err := w.CreateFormFile("file", "lanyulin"); err == nil {
		if srcfd, srcfderr := os.Open(filepath); srcfderr == nil {
			io.Copy(fw, srcfd)
			srcfd.Close()
		}
	}
	fmt.Println(b.String())

	w.Close()

	req, _ := http.NewRequest("POST", url, &b)
	req.Header.Set("Content-Type", w.FormDataContentType())

	//http.DefaultClient.Transport =
	res, reserr := http.DefaultClient.Do(req)
	if reserr != nil {
		log.Println(log.DebugLog, reserr)
		return reserr
	}

	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("bad status: %s", res.Status)
	}

	by, byerr := ioutil.ReadAll(res.Body)
	fmt.Println(string(by), byerr)
	return nil
}

func Upload(url, file string) (err error) {
	// Prepare a form that you will submit to that URL.
	var b bytes.Buffer
	w := multipart.NewWriter(&b)
	// Add your image file
	f, err := os.Open(file)
	if err != nil {
		return
	}
	defer f.Close()
	fw, err := w.CreateFormFile("image", file)
	if err != nil {
		return
	}
	if _, err = io.Copy(fw, f); err != nil {
		return
	}
	// Add the other fields
	if fw, err = w.CreateFormField("key"); err != nil {
		return
	}
	if _, err = fw.Write([]byte("KEY")); err != nil {
		return
	}
	// Don't forget to close the multipart writer.
	// If you don't close it, your request will be missing the terminating boundary.
	w.Close()

	// Now that you have a form, you can submit it to your handler.
	req, err := http.NewRequest("POST", url, &b)
	if err != nil {
		return
	}
	// Don't forget to set the content type, this will contain the boundary.
	req.Header.Set("Content-LocalId", w.FormDataContentType())

	// Submit the request
	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return
	}

	// Check the response
	if res.StatusCode != http.StatusOK {
		err = fmt.Errorf("bad status: %s", res.Status)
	}
	return
}
