from dataclasses import dataclass
from typing import Optional

from abra_python.resources.base import BaseResource


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

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

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

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

        return self.Data(response)

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

        return self.Data(response)

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

        return self.Data(response)

    @dataclass
    class Data:
        code: str
        displayname: str
        firm_id: Optional[str]
        firmoffices: list
        legalperson: bool
        id: str
        name: str
        objversion: int
        orgidentnumber: str  # ICO
        residenceaddress_id: dict
        rows: list
        vatidentnumber: str
        vatpayor: bool

        def __init__(self, data: dict):
            self.code = data.get("code")
            self.displayname = data.get("displayname")
            self.firm_id = data.get("firm_id")
            self.firmoffices = data.get('firmoffices', list)
            self.legalperson = data.get("legalperson", True)
            self.id = data.get("id")
            self.name = data.get("name")
            self.objversion = data.get("objversion", 0)
            self.orgidentnumber = data.get("orgidentnumber")  # ICO
            self.residenceaddress_id = data.get("residenceaddress_id", dict)
            self.rows = data.get('rows', list)
            self.vatidentnumber = data.get("vatidentnumber")  # DIC
            self.vatpayor = data.get("vatpayor", True)
