package db

import (
	"background/config"
	"background/logs"
	"crypto/tls"
	"crypto/x509"
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/mgo.v2"
	"io/ioutil"
	"log"
	"os"
)

var gDb Database
var blogDb Database
var gMongo *mgo.Session
func Init() {
	mysqlconf := config.GetMysqlConfig()
	blogConf := config.GetMysqlBlogConfig()
	InitMongoDb()
	blogDb = Database{Type: string(""), DB: initMysql(blogConf)}
	gDb = Database{Type: string(""), DB: initMysqlTLS(mysqlconf)}
}


func initMysql(mysqlconf *config.MysqlConfig) *sql.DB {
	cnn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8", mysqlconf.UserName, mysqlconf.Password,
		mysqlconf.Addr, mysqlconf.Db)
	log.Print("Connect to mysql " + cnn)
	_db, err := sql.Open("mysql", cnn)
	if err != nil {
		fmt.Println("connect sql server ", err.Error())
		os.Exit(200)

	}
	e := _db.Ping()
	if nil != e {
		fmt.Println(e.Error())
		os.Exit(200)
	}
	return  _db
}
func initMysqlTLS(mysqlconf *config.MysqlConfig) *sql.DB {

	rootCertPool := x509.NewCertPool()
	pem, err := ioutil.ReadFile("pem/ca.pem")
	if err != nil {
		log.Fatal(err)
	}
	if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
		log.Fatal("Failed to append PEM.")
	}
	clientCert := make([]tls.Certificate, 0, 1)
	certs, err := tls.LoadX509KeyPair("pem/client-cert.pem", "pem/client-key.pem")
	if err != nil {
		log.Fatal(err)
	}
	clientCert = append(clientCert, certs)
	mysql.RegisterTLSConfig("custom", &tls.Config{
		RootCAs: rootCertPool,
		Certificates: clientCert,
		InsecureSkipVerify: true,
	})

	cnn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8&tls=custom", mysqlconf.UserName, mysqlconf.Password,
		mysqlconf.Addr, mysqlconf.Db)
	log.Print("Connect to mysql " + cnn)
	_db, err := sql.Open("mysql", cnn)
	if err != nil {
		fmt.Println("connect sql server ", err.Error())
		os.Exit(200)

	}
	e := _db.Ping()
	if nil != e {
		fmt.Println(e.Error())
		os.Exit(200)
	}
	return  _db
}
func initMongoDb(conf *config.MongoConfig)  *mgo.Session{
	url := fmt.Sprintf("mongodb://%s:%s@%s:%d/%s",conf.UserName,conf.Password,conf.Addr,conf.Port,conf.Db)
	log.Print("connect to url " + url)
	logs.Debug("connect to url " + url)

	mgo,err := mgo.Dial(url)
	if nil != err{
		logs.Error(err.Error())
		return nil
	}
	return mgo
}

func GetMysqlClient() *Database {
	return &gDb
}
func GetBlogMysql()  *Database{
	return  &blogDb
}
func GetMongoDb() *mgo.Session {
	return gMongo
}
func InitMongoDb()  {
	mongoConf := config.GetMongoDBConfig()
	gMongo = initMongoDb(mongoConf)
	if gMongo == nil{
		log.Print("error mongo initial")
		os.Exit(25)
	}

}