package main

import (
	"encoding/json"
	"fmt"
)

//MediaID : json response for uploading media
type MediaID struct {
	Type         string `json:"type"`
	MediaID      string `json:"media_id"`
	CreateAt     int64  `json:"created_at"`
	ThumbMediaID string `json:"thumb_media_id"`
}

func uploadImage(filename string) (mediaid string) {
	url, _ := getPostImageURL()

	jstr, _ := postFileForm(filename, url, "media")
	//{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
	var m = MediaID{}
	json.Unmarshal([]byte(jstr), &m)
	mediaid = m.MediaID
	return
}

func uploadVideo(filename string) (mediaid string) {
	url, _ := getPostVideoURL()

	jstr, _ := postFileForm(filename, url, "media")
	//{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
	var m = MediaID{}
	json.Unmarshal([]byte(jstr), &m)
	mediaid = m.MediaID
	return

}

func uploadVoice(path string) (mediaID string) {
	url, _ := getPostVoiceURL()
	jstr, _ := postFileForm(path, url, "media")
	var m = MediaID{}
	json.Unmarshal([]byte(jstr), &m)
	mediaID = m.MediaID
	return
}

func uploadThumb(path string) (mediaID string) {
	url, _ := getPostThumbURL()
	jstr, _ := postFileForm(path, url, "media")
	var m = MediaID{}
	json.Unmarshal([]byte(jstr), &m)
	mediaID = m.ThumbMediaID
	return
}

func checkImageSanity() bool {
	//TODO
	//check file size should < 2M
	fmt.Println(" should check image file size")

	return true
}

func getPostImageURL() (url string, err error) {
	return getMediaPostURL("image")
}

func getPostVoiceURL() (url string, err error) {
	return getMediaPostURL("voice")
}

func getPostVideoURL() (url string, err error) {
	return getMediaPostURL("video")
}

func getPostThumbURL() (url string, err error) {
	return getMediaPostURL("thumb")
}

func getMediaPostURL(t string) (url string, err error) {
	atk, err := GetAccessToken()
	if err != nil {
		url = ""
	} else {
		url = fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", atk, t)
	}
	return
}

func saveMedia2File(mediaID string) (filename string, err error) {

	url := mediaID2URL(mediaID)
	file, _, e := saveURL(url)
	if e != nil {
		return "", e
	}
	fmt.Println("save media to " + file)

	return file, nil
}

func mediaID2URL(mediaID string) (url string) {
	atk, _ := GetAccessToken()
	url = fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", atk, mediaID)
	return
}
