from defence360agent.model import instance
from defence360agent.rpc_tools import lookup
from defence360agent.rpc_tools.utils import run_in_executor_decorator
from defence360agent.utils import Scope
from im360.model.firewall import WhitelistedCrawler


class WhitelistedCrawlersEndpoints(lookup.RootEndpoints):
    SCOPE = Scope.IM360

    @lookup.bind("whitelisted-crawlers", "add")
    @run_in_executor_decorator
    def add_whitelisted_crawler(self, description, domains):
        WhitelistedCrawler.add(description, domains)

    @lookup.bind("whitelisted-crawlers", "delete")
    @run_in_executor_decorator
    def delete_whitelisted_crawlers(self, ids):
        with instance.db.atomic():
            for id in ids:
                WhitelistedCrawler.delete().where(
                    WhitelistedCrawler.id == id
                ).execute()

    @lookup.bind("whitelisted-crawlers", "list")
    @run_in_executor_decorator
    def list_whitelisted_crawlers(self, limit, offset):
        return WhitelistedCrawler.fetch(limit, offset)
