using DotNext;
using LinqToDB;
using LinqToDB.Data;

namespace Database;

/// <summary>
/// 应用程序数据连接类，用于与数据库交互
/// </summary>
public class AppDataConnection : DataConnection
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    static readonly string DATABASE_FILEPATH = $"{Global.DataPath}/Database.sqlite";

    static readonly LinqToDB.DataOptions options =
        new LinqToDB.DataOptions().UseSQLite($"Data Source={DATABASE_FILEPATH}");

    /// <summary>
    /// 用户表
    /// </summary>
    public ITable<User> UserTable => this.GetTable<User>();

    /// <summary>
    /// FPGA 板子表
    /// </summary>
    public ITable<Board> BoardTable => this.GetTable<Board>();

    /// <summary>
    /// 实验表
    /// </summary>
    public ITable<Exam> ExamTable => this.GetTable<Exam>();

    /// <summary>
    /// 资源表（统一管理实验资源、用户比特流等）
    /// </summary>
    public ITable<Resource> ResourceTable => this.GetTable<Resource>();

    /// <summary>
    /// 初始化应用程序数据连接
    /// </summary>
    public AppDataConnection() : base(options)
    {
        var filePath = Path.GetDirectoryName(DATABASE_FILEPATH);
        if (!string.IsNullOrEmpty(filePath) && !Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        if (!Path.Exists(DATABASE_FILEPATH))
        {
            logger.Info($"数据库文件不存在，正在创建新数据库: {DATABASE_FILEPATH}");
            LinqToDB.DataProvider.SQLite.SQLiteTools.CreateDatabase(DATABASE_FILEPATH);
            this.CreateAllTables();
            var user = new User()
            {
                Name = "Admin",
                EMail = "selfconfusion@gmail.com",
                Password = "12345678",
                Permission = Database.UserPermission.Admin,
            };
            this.Insert(user);
            logger.Info("默认管理员用户已创建");
        }
        else
        {
            logger.Info($"数据库连接已建立: {DATABASE_FILEPATH}");
        }
    }

    /// <summary>
    /// 创建所有数据库表
    /// </summary>
    public void CreateAllTables()
    {
        logger.Info("正在创建数据库表...");
        this.CreateTable<User>();
        this.CreateTable<Board>();
        this.CreateTable<Exam>();
        this.CreateTable<Resource>();
        logger.Info("数据库表创建完成");
    }

    /// <summary>
    /// 删除所有数据库表
    /// </summary>
    public void DropAllTables()
    {
        logger.Warn("正在删除所有数据库表...");
        this.DropTable<User>();
        this.DropTable<Board>();
        this.DropTable<Exam>();
        this.DropTable<Resource>();
        logger.Warn("所有数据库表已删除");
    }


}
