package test

import (
	"fmt"
	"io"
	"os"
	"testing"
)

func TestCreateLob(t *testing.T) {
	_, err := db.Exec("CREATE TABLE gotab4 (image BLOB);")
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
	}
}
func TestInsertLob(t *testing.T) {
	// 打开文件
	file, err := os.Open("C0077.MP4")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	// 确保在函数结束时关闭文件
	defer file.Close()
	// 读取文件内容
	fileContent, err := io.ReadAll(file)
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}

	_, err = db.Exec("INSERT INTO gotab4 VALUES(?);", fileContent)
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
	}
}

func TestSelecttLob(t *testing.T) {
	rows, err := db.Query("select * from gotab3;")
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
		return
	}

	column, err := rows.Columns()
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
		return
	}
	rows_value := make([]interface{}, len(column))
	for key, _ := range rows_value {
		dest := make([]byte, 1000000)
		rows_value[key] = &dest
	}

	for rows.Next() {
		rows.Scan(rows_value...)

		for _, v := range rows_value {
			fmt.Printf("结果: %s\t", string(*(v.(*[]byte))))
		}
		fmt.Printf("\n")
	}

	rows.Close()
	db.Close()
}

func TestSelecttLobToSave(t *testing.T) {
	rows, err := db.Query("select * from gotab4;")
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
		return
	}

	column, err := rows.Columns()
	if err != nil {
		fmt.Printf("[ERROR] %s\n", err.Error())
		return
	}
	rows_value := make([]interface{}, len(column))
	for key, _ := range rows_value {
		dest := make([]byte, 1000000)
		rows_value[key] = &dest
	}

	for rows.Next() {
		rows.Scan(rows_value...)

		for _, v := range rows_value {
			//fmt.Printf("结果: %s\t", string(*(v.(*[]byte))))
			SaveToFile(*(v.(*[]byte)), "Ct.MP4")
		}
		fmt.Printf("\n")
	}

	rows.Close()
	db.Close()
}

// SaveToFile 将字节切片保存到文件中
func SaveToFile(data []byte, filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = file.Write(data)
	if err != nil {
		return err
	}

	return nil
}
