package main

import (
	"github.com/tangs-drm/go-tool/config"
	"github.com/tangs-drm/go-tool/log"
	"fmt"
	"view/viewapi"
	thttp "github.com/tangs-drm/go-tool/http"
	"net/http"
	"github.com/tangs-drm/go-tool/dbm"
	"view/viewdb"
	"gopkg.in/mgo.v2"
)

func main() {

	cfgPath := "config.conf"
	cfg := config.NewConfig()
	err := cfg.Config(cfgPath)
	if err != nil {
		fmt.Printf("[MAIN] read config(%v) error ->(%v) \n", cfgPath, err)
		log.Error("[MAIN] read config(%v) error ->(%v)", cfgPath, err)
		return
	}
	cfg.Print()

	// 连接数据库

	// 连接mongo
	session, err := mgo.Dial(cfg.String("mongo_db_url"))
	if err != nil {
		fmt.Printf("[MAIN] dail to db with db_url(%v) error ->(%v) \n", cfg.String("db_url"), err)
		log.Error("[MAIN] dail to db with db_url(%v) error ->(%v)", cfg.String("db_url"), err)
		return
	}

	if len(cfg.String("mongodb_name")) < 1 {
		fmt.Printf("[MAIN] get db name empty")
		log.Error("[MAIN] get db name empty")
		return
	}
	db := session.DB(cfg.String("mongodb_name"))
	viewdb.SetC(db)

	// 连接mysql
	_, err = dbm.Default(cfg.String("mysql_db_url"))
	if err != nil {
		fmt.Printf("[MAIN] connect mysql with db_url(%v) error ->(%v)\n", cfg.String("db_url"), err)
		log.Error("[MAIN] connect mysql with db_url(%v) error ->(%v)", cfg.String("db_url"), err)
		return
	}
	err = viewdb.InitDb()
	if err != nil {
		fmt.Printf("[MAIN] init mysql error ->(%v)\n", err)
		log.Error("[MAIN] init mysql error ->(%v)", err)
		return
	}

	// 创建http对象
	mux := thttp.NewServerMux()

	viewapi.Router(mux)

	fmt.Printf("[MAIN] process will start with port: %v \n", cfg.String("listen_port"))
	log.Debug("[MAIN] process will start with port: %v", cfg.String("listen_port"))

	mux.Handle("/", http.FileServer(http.Dir("www")))
	//mux.Handle("/common", http.StripPrefix("/common", http.FileServer(http.Dir("www/common"))))
	//mux.Handle("/", http.FileServer(http.Dir("www")))
	//mux.Handle("/common/jquery-3.2.1.min/", http.StripPrefix("/common/jquery-3.2.1.min", http.FileServer(http.Dir("www"))))
	//mux.Handle("/js", http.FileServer(http.Dir("www/js")))

	fmt.Println(thttp.ListenAndServe(cfg.String("listen_port"), mux))
	//http.Handle("/", http.FileServer(http.Dir(".")))
	//http.ListenAndServe(cfg.String("listen_port"), mux)
}