from dataclasses import dataclass
from datetime import datetime

from abra_python.resources.base import BaseResource


class Period(BaseResource):
    def list(self, query: dict = None):
        if query is None:
            query = {'take': 10}

        response = self.requestor.request(
            method='GET',
            endpoint_url='/periods',
            query=query
        )

        return [
            self.Data(item)
            for item in response
        ]

    def get(self, period_id: str):
        response = self.requestor.request(
            method='GET',
            endpoint_url=f'/periods/{period_id}'
        )

        return self.Data(response)

    def create(self, payload: dict):
        response = self.requestor.request(
            method='POST',
            endpoint_url='/periods',
            payload=payload
        )

        return self.Data(response)

    def update(self, period_id: str, payload: dict):
        response = self.requestor.request(
            method='PUT',
            endpoint_url=f'/periods/{period_id}',
            payload=payload
        )

        return self.Data(response)

    @dataclass
    class Data:
        beginnings: bool
        closing: bool
        code: str
        date_from: datetime
        date_to: datetime
        id: str
        name: str
        objversion: int
        sequence_number: int

        def __init__(self, data):
            self.beginnings = data.get("beginnings")
            self.closing = data.get("closing")
            self.code = data.get("code")
            self.date_from = data.get("datefrom$date")
            self.date_to = data.get("dateto$date")
            self.id = data.get("id")
            self.name = data.get("name")
            self.objversion = data.get("objversion")
            self.sequence_number = data.get("sequencenumber")
