package util

import (
	"database/sql"
	"fmt"
	"strconv"

	"github.com/go-sql-driver/mysql"
)

func MysqlImporter(conf *MySQLConfig, filePath, table, fields string) int64 {
	dsn := conf.Mysql_User + ":" + conf.Mysql_Password +
		"@tcp(" + conf.Mysql_Host + ":" + strconv.Itoa(conf.Mysql_Port) + ")/" +
		conf.Mysql_Name + "?charset=utf8&parseTime=True&allowAllFiles=true"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return 0
	}
	defer db.Close()
	mysql.RegisterLocalFile(filePath)
	strSQL := fmt.Sprintf(`LOAD DATA LOCAL INFILE '%s' INTO TABLE %s 
		CHARACTER SET UTF8 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (%s)`,
		filePath, table, fields)
	result, err_exec := db.Exec(strSQL)
	if err_exec != nil {
		return 0
	}
	rowsaffected, _ := result.RowsAffected()
	return rowsaffected
}
