package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"path/filepath"
	"strings"
)

func debug_sendmail(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	if req.Method == "GET" {
		//视图输出
		files := []string{
			filepath.Join(Cfg.TmplDir, "debug", "sendmail.tmpl"),
			filepath.Join(Cfg.TmplDir, "header.tmpl"),
			filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
		}
		tmpl, err := template.New("sendmail.tmpl").Funcs(TmplFuncMap).ParseFiles(files...)
		if err != nil {
			io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error()))
		} else {
			tmpl.Execute(resp, struct {
				Sess  *Session
				Req   *http.Request
				Title string
			}{
				sess,
				req,
				"Debug - 邮件测试",
			})
		}
	} else {
		sendto := req.PostForm.Get("sendto")
		title := req.PostForm.Get("title")
		content := req.PostForm.Get("content")
		if sendto == "" {
			ret, _ := json.Marshal(ErrorRet{Errno: 1, Error: "收件人不能为空"})
			resp.Write(ret)
			return
		}
		if title == "" {
			ret, _ := json.Marshal(ErrorRet{Errno: 2, Error: "标题不能为空"})
			resp.Write(ret)
			return
		}
		if content == "" {
			ret, _ := json.Marshal(ErrorRet{Errno: 3, Error: "内容不能为空"})
			resp.Write(ret)
			return
		}
		req := MailRequest{
			sendto:  strings.Split(sendto, ";"),
			title:   title,
			content: content,
		}
		Sender.Push(&req)
		ret, _ := json.Marshal(ErrorRet{Errno: 0, Error: ""})
		resp.Write(ret)
	}
}
