package sm

import (
	"database/sql"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"time"

	"be.ems/lib/log"
	"be.ems/lib/services"
	"be.ems/restagent/config"
	_ "github.com/go-sql-driver/mysql"
)

var (
	// Get OMC local time
	UriOMCLocalTime = config.DefaultUriPrefix + "/systemManagement/{apiVersion}/elementType/OMC/objectType/time"

	CustomUriOMCLocalTime = config.UriPrefix + "/systemManagement/{apiVersion}/elementType/OMC/objectType/time"
)

type OMCLocalTime struct {
	Timestamp int64 `json:"timestamp"` // 时间戳 (单位:毫秒)
	TimeZone  int   `json:"timeZone"`  // 本地时区偏移（单位：秒）
}

func GetOMCLocalTime(w http.ResponseWriter, r *http.Request) {
	log.Debug("GetOMCLocalTime processing... ")

	_, err := services.CheckFrontValidRequest(w, r)
	if err != nil {
		log.Error("Http request error:", err)
		return
	}

	t := time.Now()
	_, offset := t.Zone()

	localTime := OMCLocalTime{
		Timestamp: t.UnixMilli(),
		TimeZone:  offset,
	}
	response := services.DataResponse{
		Data: localTime,
	}
	services.ResponseWithJson(w, http.StatusOK, response)
}

var dbConfig = config.GetYamlConfig().Database

func DatabaseWhoreBackup() {
	// MySQL数据库连接信息
	sqlStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true&loc=Local",
		dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name)
	db, err := sql.Open("mysql", sqlStr)
	if err != nil {
		log.Error("Failed to connect to database:", err)
		return
	}
	defer db.Close()

	// 备份SQL文件路径
	backupFile := dbConfig.Backup + "/" + "whore_backup_" + dbConfig.Name + ".sql"

	// 执行mysqldump命令进行备份
	cmd := exec.Command("mysqldump", "-u", dbConfig.User, "-p"+dbConfig.Password, "-h", dbConfig.Host, dbConfig.Name)
	output, err := cmd.Output()
	if err != nil {
		log.Error("Failed to execute mysqldump command:", err)
		return
	}

	// 将备份结果写入SQL文件
	file, err := os.Create(backupFile)
	if err != nil {
		log.Error("Failed to create backup file:", err)
		return
	}
	defer file.Close()

	_, err = file.Write(output)
	if err != nil {
		log.Error("Failed to write backup file:", err)
		return
	}

	log.Info("Backup completed successfully.")
}

func DatabaseIncrementalBackup() {
	// MySQL数据库连接信息
	sqlStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true&loc=Local",
		dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name)
	db, err := sql.Open("mysql", sqlStr)
	if err != nil {
		log.Error("Failed to connect to database:", err)
		return
	}
	defer db.Close()

	// 备份SQL文件路径
	backupFile := dbConfig.Backup + "/" + "incremental_backup_" + dbConfig.Name + ".sql"

	// 上次备份的时间点
	lastBackupTime := time.Date(2022, time.January, 1, 0, 0, 0, 0, time.Local)

	// 构建增量备份SQL语句
	query := fmt.Sprintf("SELECT * FROM table WHERE modified_at > '%s'", lastBackupTime.Format("2006-01-02 15:04:05"))

	// 执行查询
	rows, err := db.Query(query)
	if err != nil {
		log.Error("Failed to execute query:", err)
		return
	}
	defer rows.Close()

	// 创建增量备份SQL文件
	file, err := os.Create(backupFile)
	if err != nil {
		log.Error("Failed to create backup file:", err)
		return
	}
	defer file.Close()

	// 将查询结果写入SQL文件
	for rows.Next() {
		var data string
		err := rows.Scan(&data)
		if err != nil {
			log.Error("Failed to scan row:", err)
			return
		}

		_, err = file.WriteString(data + "\n")
		if err != nil {
			log.Error("Failed to write backup file:", err)
			return
		}
	}

	log.Info("Incremental backup completed successfully.")
}
