package main

import (
	"net/http"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/dalu/wiki/public"
	"github.com/dalu/wiki/storage"
	"github.com/dalu/wiki/storage/mongo"
	"github.com/dalu/wiki/template"
	"github.com/dalu/wiki/wiki"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func main() {
	log := logrus.New()
	ms, e := mgo.Dial("localhost")
	if e != nil {
		log.Fatal("could not connect to mongodb", e.Error())
	}
	defer ms.Close()

	mongostore := mongo.New(ms, mongo.Config{Database: "wiki"})
	if e := initializeWiki(mongostore); e != nil {
		log.Fatal("initializeWiki: ", e.Error())
	}

	renderer := template.New(true)

	mux := http.NewServeMux()

	wikiHandler := wiki.NewWikiHandler(mongostore, renderer, log)
	mux.Handle(wiki.DefaultMountPath, http.StripPrefix(wiki.DefaultMountPath, wikiHandler))

	mux.Handle(public.CSSMountpoint, public.CSSHandler)
	mux.Handle(public.JSMountpoint, public.JSHandler)

	server := &http.Server{
		Handler:      mux,
		Addr:         ":8080",
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}

	log.Fatal(server.ListenAndServe())
}

func initializeWiki(s storage.Interface) error {
	_, e := s.GetTermByName("")
	if e != nil {
		if e == mgo.ErrNotFound {
			t1 := new(storage.Term)
			t1.ID = bson.NewObjectId()
			t1.Language = "en" //TODO: create a Main_Page for all languages
			t1.Redirect = "Main_Page"
			t2 := new(storage.Term)
			t2.ID = bson.NewObjectId()
			t2.Language = "en"
			t2.Name = "Main Page"
			t2.Slug = "Main_Page"
			r := new(storage.Revision)
			r.ID = bson.NewObjectId()
			r.PublishDate = time.Now()
			r.AuthorIP = "127.0.0.1"
			r.TermID = t2.ID.Hex()
			r.Text = "This is the main apge"
			t2.CurrentRevisionID = r.ID.Hex()
			if e := s.CreateTerm(t1); e != nil {
				return e
			}
			if e := s.CreateTerm(t2); e != nil {
				return e
			}

			if e := s.CreateRevision(r); e != nil {
				return e
			}
		} else {
			return e
		}
	}
	return nil
}
