from pathlib import Path
from im360.subsys import csf

CSF_COOP_STRATEGY = Path("/var/imunify360/.csf_coop")
PRIMARY_IDS_STRATEGY = Path("/var/imunify360/.primary_ids")


class Strategy:
    PRIMARY_IDS_STRATEGY = "PRIMARY_IDS"
    CSF_COOP_STRATEGY = "CSF_COOP"
    UNKNOWN = "UNKNOWN"

    current = UNKNOWN

    @classmethod
    async def detect(cls):
        csf_running = await csf.is_running()
        if csf_running:
            return cls.CSF_COOP_STRATEGY
        else:
            return cls.PRIMARY_IDS_STRATEGY

    @classmethod
    def save(cls, new_strategy):
        if new_strategy is cls.CSF_COOP_STRATEGY:
            CSF_COOP_STRATEGY.touch()
            PRIMARY_IDS_STRATEGY.unlink(missing_ok=True)
        elif new_strategy is cls.PRIMARY_IDS_STRATEGY:
            PRIMARY_IDS_STRATEGY.touch()
            CSF_COOP_STRATEGY.unlink(missing_ok=True)
        else:
            PRIMARY_IDS_STRATEGY.unlink(missing_ok=True)
            CSF_COOP_STRATEGY.unlink(missing_ok=True)

    @classmethod
    def get(cls):
        if CSF_COOP_STRATEGY.exists():
            return cls.CSF_COOP_STRATEGY
        elif PRIMARY_IDS_STRATEGY.exists():
            return cls.PRIMARY_IDS_STRATEGY
        return cls.UNKNOWN
