from pydantic import BaseModel
from typing import List, Optional

from models.attribute import Attribute

from lib.irt.item_response_function import ItemResponseFunction
from lib.irt.item_information_function import ItemInformationFunction

class Item(BaseModel):
    id: int
    passage_id: Optional[int]
    workflow_state: Optional[str]
    attributes: List[Attribute]
    b_param: float = 0.00

    def iif(self, solver_run, theta):
        return ItemInformationFunction(solver_run.irt_model).calculate(
            b_param=self.b_param, theta=theta)

    def irf(self, solver_run, theta):
        return ItemResponseFunction(solver_run.irt_model).calculate(
            b_param=self.b_param, theta=theta)

    def get_attribute(self, ref_attribute):
        for attribute in self.attributes:
            if attribute.id == ref_attribute.id and attribute.value.lower(
            ) == ref_attribute.value.lower():
                return attribute.value
        return False

    def attribute_exists(self, ref_attribute):
        for attribute in self.attributes:
            if attribute.id == ref_attribute.id and attribute.value.lower(
            ) == ref_attribute.value.lower():
                return True
        return False

    def iif_irf_sum(self, solver_run):
        return self.__iif_sum(solver_run) + self.__irf_sum(solver_run)

    def __iif_sum(self, solver_run):
        total = 0

        for target in solver_run.objective_function.tif_targets:
            total += self.iif(solver_run, target.theta)

        return total

    def __irf_sum(self, solver_run):
        total = 0

        for target in solver_run.objective_function.tif_targets:
            total += self.irf(solver_run, target.theta)

        return total