namespace MinicsConsole.Helper;

public class DataBaseSwitch(OrmCollections orms, HardWareMonitor hardWareMonitor, BasicInfo basicInfo)
{
    public bool SwitchDataBaseLibrary(out string? newDBName)
    {
        newDBName = null;
        if (string.IsNullOrEmpty(basicInfo.DBConnectionString))
            return false;

        if (orms.MainORM is null)
            return false;

        List<UserInfo> oldusers = [];
        orms.MainORM.Query<UserInfo>("UserAuthority", oldusers.AddRange).Wait();

        int start = basicInfo.DBConnectionString.IndexOf('=') + 1;
        int end = basicInfo.DBConnectionString.IndexOf(';');

        string part1 = basicInfo.DBConnectionString[..start];
        string part2 = basicInfo.DBConnectionString[end..];
        newDBName = $"{DateTime.Now:yyyy_MM_dd_HH_mm_ss}";
        string newDBString = $"{part1}{newDBName}{part2}";

        IORM orm_new = new SqlSugarCustom();

        if (!orm_new.Initialize() || !orm_new.Open(newDBString, DbType.PostgreSQL))
            return false;

        basicInfo.DBConnectionString = newDBString;
        BaseConfigFileLoader.Save(basicInfo);

        orm_new.CreateTable<UserInfo>("UserAuthority");
        oldusers.ForEach(userInfo => orm_new.Insert("UserAuthority", userInfo));

        IORM orm_old = orms.MainORM;
        orms.MainORM = orm_new;
        orm_old.Dispose();

        hardWareMonitor.FullyReset();

        return true;
    }
}