from distutils.version import LooseVersion

from ppms import ppms
from ppms.constants import DBMS_MSSQL
from ppms.migration import SQLPacket, PacketCategory, DBMSDependency


class AllowDelayedDurability(SQLPacket):
    """SQL Server: allow delayed durability


    Only necessary on SQL Server. This is bound to fail on SQL Server prior to 2014
    """
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 20392

    def get_dependencies(self):
        return (DBMSDependency(DBMS_MSSQL),)

    def fix(self, packet_runner):
        dbms = ppms.db_get_dbms_name()
        if dbms != DBMS_MSSQL:
            self.log('This packet is not needed for this DBMS')
            return self.unnecessary()

        db_version = self.select_or_log("SELECT CAST(SERVERPROPERTY('ProductVersion') as VARCHAR(128))")[0][0]
        if LooseVersion(db_version) >= LooseVersion('12'):
            try:
                db_name = self.select_or_log("SELECT DB_NAME()")[0][0]
                ppms.db_commit()
                query = """ALTER DATABASE {db_name} SET DELAYED_DURABILITY = ALLOWED""".format(db_name=db_name)
                self.modify_and_log(query)
                return self.success()
            except ppms.DatabaseError as e:
                if "sqlserver" in str(e):
                    return self.fail(
                        """permissions are required to perform "ALTER DATABASE {db_name} SET DELAYED_DURABILITY = 
                        ALLOWED" the DB admin should please execute it manually""")
                else:
                    raise e
        else:
            self.log('The current SQL Server version does not support DELAYED_DURABILITY')
            return self.unnecessary()
