package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type crmdLiveCast struct {
	crmdEntityBase
	Youtube     string `json:"youtube,omitempty"`
	Description string `json:"description,omitempty"`
}

func spaLiveCastHandler(w http.ResponseWriter, r *http.Request) {
	castID := ""
	q, err := url.ParseQuery(r.URL.RawQuery)
	if err == nil {
		castIDs, ok := q["id"]
		if ok {
			castID = castIDs[0]
		}
	}

	if castID == "" {
		responseDefaultLiveCast(w)
		return
	}

	//castID = "5967812b87eb10564"
	entity, err := crmGetEntity("Livecast", castID)
	if err != nil || entity == nil {
		response404Handler(w)
		return
	}

	cast := entity.(crmdLiveCast)

	cast.youtubeVideo(w)
}

func (m crmdLiveCast) youtubeVideo(w http.ResponseWriter) {
	tTest := template.New("livecast")
	str, err := ioutil.ReadFile("spa/livecast.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Formating information not available.")
		return
	}
	tTest, err = tTest.Parse(string(str))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Formating instruction invalid")
		return
	}

	err = tTest.Execute(w, m)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Monkey runs into our computer room...")
		log.Println("ERROR: Template execution on spa/Edit, failed \n" + err.Error())
	}
}

func responseDefaultLiveCast(w http.ResponseWriter) {
	cast := crmdLiveCast{}

	cast.Youtube = "https://www.youtube.com/embed/8r9zR27Kzho"
	cast.Name = "暂无直播"
	cast.Description = `
	直播活动，和校友会活动息息相关，方便在不同地域的校友积极参加，同时留下宝贵的影响资料，供后来的校友们参考。在没有直播的情况下， 校友会随机选取哈工大的宣传片，校友们的个人简介，以及校友会的宣传片放映。
	`
	cast.youtubeVideo(w)
}
