#
# Copyright (C) 2019-2025  Leo P. Singer <leo.singer@ligo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
from os.path import join


class Resource:
    path = None

    def __init__(self, parent=None, path=None):
        self.client = parent.client
        self.parent = parent
        self.url = self.parent.url
        if path is None:
            path = self.path
        if path is not None:
            self.url = join(self.url, str(path))

    async def get(self, **kwargs):
        return (await self.client.get(self.url, **kwargs, follow_redirects=True)).json()


class Deletable:
    async def delete(self, key):
        await self.client.delete(join(self.url, str(key)), follow_redirects=True)


class Mutable:
    async def create_or_update(self, key, **kwargs):
        if key is None:
            return (
                await self.client.post(self.url, **kwargs, follow_redirects=True)
            ).json()
        else:
            return await self.client.put(
                join(self.url, str(key)), **kwargs, follow_redirects=True
            )

    async def create(self, **kwargs):
        return await self.create_or_update(None, **kwargs)

    async def update(self, key, **kwargs):
        return await self.create_or_update(key, **kwargs)


class Mapping:
    def __getitem__(self, key):
        return self.mapped_class(self, key)
