# -*- coding: utf-8; -*-
################################################################################
#
#  WuttaFarm --Web app to integrate with and extend farmOS
#  Copyright © 2026 Lance Edgar
#
#  This file is part of WuttaFarm.
#
#  WuttaFarm 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.
#
#  WuttaFarm 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
#  WuttaFarm.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Custom form widgets for WuttaFarm
"""

import json

import colander

from wuttaweb.db import Session
from wuttaweb.forms.schema import ObjectRef, WuttaSet, WuttaList
from wuttaweb.forms.widgets import NotesWidget


class AnimalTypeRef(ObjectRef):
    """
    Custom schema type for a
    :class:`~wuttafarm.db.model.animals.AnimalType` reference field.

    This is a subclass of
    :class:`~wuttaweb:wuttaweb.forms.schema.ObjectRef`.
    """

    @property
    def model_class(self):  # pylint: disable=empty-docstring
        """ """
        model = self.app.model
        return model.AnimalType

    def sort_query(self, query):  # pylint: disable=empty-docstring
        """ """
        return query.order_by(self.model_class.name)

    def get_object_url(self, obj):  # pylint: disable=empty-docstring
        """ """
        animal_type = obj
        return self.request.route_url("animal_types.view", uuid=animal_type.uuid)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import AnimalTypeRefWidget

        kwargs["factory"] = AnimalTypeRefWidget
        return super().widget_maker(**kwargs)


class LogQuick(WuttaSet):

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import LogQuickWidget

        return LogQuickWidget(**kwargs)


class LogRef(ObjectRef):
    """
    Custom schema type for a
    :class:`~wuttafarm.db.model.log.Log` reference field.

    This is a subclass of
    :class:`~wuttaweb:wuttaweb.forms.schema.ObjectRef`.
    """

    @property
    def model_class(self):  # pylint: disable=empty-docstring
        """ """
        model = self.app.model
        return model.Log

    def sort_query(self, query):  # pylint: disable=empty-docstring
        """ """
        return query.order_by(self.model_class.message)

    def get_object_url(self, obj):  # pylint: disable=empty-docstring
        """ """
        log = obj
        return self.request.route_url(f"logs_{log.log_type}.view", uuid=log.uuid)


class FarmOSUnitRef(colander.SchemaType):

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSUnitRefWidget

        return FarmOSUnitRefWidget(**kwargs)


class FarmOSRef(colander.SchemaType):

    def __init__(self, request, route_prefix, *args, **kwargs):
        self.values = kwargs.pop("values", None)
        super().__init__(*args, **kwargs)
        self.request = request
        self.route_prefix = route_prefix

    def get_values(self):
        if callable(self.values):
            self.values = self.values()
        return self.values

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        # nb. keep a ref to this for later use
        node.model_instance = appstruct

        # serialize to PK as string
        return appstruct["uuid"]

    def deserialize(self, node, cstruct):
        if not cstruct:
            return colander.null

        # nb. deserialize to PK string, not dict
        return cstruct

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSRefWidget

        if not kwargs.get("readonly"):
            if "values" not in kwargs:
                if values := self.get_values():
                    kwargs["values"] = values

        return FarmOSRefWidget(self.request, self.route_prefix, **kwargs)


class FarmOSRefs(WuttaSet):

    def __init__(self, request, route_prefix, *args, **kwargs):
        super().__init__(request, *args, **kwargs)
        self.route_prefix = route_prefix

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null
        return appstruct

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSRefsWidget

        return FarmOSRefsWidget(self.request, self.route_prefix, **kwargs)


class FarmOSAssetRefs(WuttaSet):

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSAssetRefsWidget

        return FarmOSAssetRefsWidget(self.request, **kwargs)


class FarmOSLocationRefs(WuttaSet):

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSLocationRefsWidget

        return FarmOSLocationRefsWidget(self.request, **kwargs)


class FarmOSQuantityRefs(WuttaSet):

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSQuantityRefsWidget

        return FarmOSQuantityRefsWidget(**kwargs)


class FarmOSTaxonomyTerms(colander.SchemaType):
    """
    Schema type which can represent multiple taxonomy terms.
    """

    route_prefix = None

    def __init__(self, request, route_prefix=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        if route_prefix:
            self.route_prefix = route_prefix

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null
        return appstruct

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import FarmOSTaxonomyTermsWidget

        return FarmOSTaxonomyTermsWidget(self.request, self.route_prefix, **kwargs)


class FarmOSEquipmentTypeRefs(FarmOSTaxonomyTerms):

    route_prefix = "farmos_equipment_types"


class FarmOSPlantTypes(colander.SchemaType):

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):  # pylint: disable=empty-docstring
        """ """
        from wuttafarm.web.forms.widgets import FarmOSPlantTypesWidget

        return FarmOSPlantTypesWidget(self.request, **kwargs)


class LandTypeRef(ObjectRef):
    """
    Custom schema type for a
    :class:`~wuttafarm.db.model.land.LandType` reference field.

    This is a subclass of
    :class:`~wuttaweb:wuttaweb.forms.schema.ObjectRef`.
    """

    @property
    def model_class(self):  # pylint: disable=empty-docstring
        """ """
        model = self.app.model
        return model.LandType

    def sort_query(self, query):  # pylint: disable=empty-docstring
        """ """
        return query.order_by(self.model_class.name)

    def get_object_url(self, obj):  # pylint: disable=empty-docstring
        """ """
        land_type = obj
        return self.request.route_url("land_types.view", uuid=land_type.uuid)


class TaxonomyTermRefs(WuttaList):
    """
    Generic schema type for a field which can reference multiple
    taxonomy terms.
    """

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        terms = []
        for term in appstruct:
            terms.append(
                {
                    "uuid": str(term.uuid),
                    "name": term.name,
                }
            )
        return terms


class EquipmentTypeRefs(TaxonomyTermRefs):

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import EquipmentTypeRefsWidget

        return EquipmentTypeRefsWidget(self.request, **kwargs)


class PlantTypeRefs(WuttaSet):
    """
    Schema type for Plant Types field (on a Plant Asset).
    """

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        return [uuid.hex for uuid in appstruct]

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import PlantTypeRefsWidget

        model = self.app.model
        session = Session()

        if "values" not in kwargs:
            plant_types = (
                session.query(model.PlantType).order_by(model.PlantType.name).all()
            )
            values = [(pt.uuid.hex, str(pt)) for pt in plant_types]
            kwargs["values"] = values

        return PlantTypeRefsWidget(self.request, **kwargs)


class MaterialTypeRefs(colander.List):
    """
    Schema type for Material Types field (on a Material Asset).
    """

    def __init__(self, request):
        super().__init__()
        self.request = request
        self.config = self.request.wutta_config
        self.app = self.config.get_app()

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        mtypes = []
        for mtype in appstruct:
            mtypes.append(
                {
                    "uuid": mtype.uuid.hex,
                    "name": mtype.name,
                }
            )
        return mtypes

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import MaterialTypeRefsWidget

        return MaterialTypeRefsWidget(self.request, **kwargs)


class SeasonRefs(WuttaSet):
    """
    Schema type for Plant Types field (on a Plant Asset).
    """

    def serialize(self, node, appstruct):
        if not appstruct:
            return []

        return [season.uuid.hex for season in appstruct]

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import SeasonRefsWidget

        model = self.app.model
        session = Session()

        if "values" not in kwargs:
            seasons = session.query(model.Season).order_by(model.Season.name).all()
            values = [(s.uuid.hex, str(s)) for s in seasons]
            kwargs["values"] = values

        return SeasonRefsWidget(self.request, **kwargs)


class StructureType(colander.SchemaType):

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):  # pylint: disable=empty-docstring
        """ """
        from wuttafarm.web.forms.widgets import StructureWidget

        return StructureWidget(self.request, **kwargs)


class StructureTypeRef(ObjectRef):
    """
    Custom schema type for a
    :class:`~wuttafarm.db.model.structures.Structure` reference field.

    This is a subclass of
    :class:`~wuttaweb:wuttaweb.forms.schema.ObjectRef`.
    """

    @property
    def model_class(self):  # pylint: disable=empty-docstring
        """ """
        model = self.app.model
        return model.StructureType

    def sort_query(self, query):  # pylint: disable=empty-docstring
        """ """
        return query.order_by(self.model_class.name)

    def get_object_url(self, obj):  # pylint: disable=empty-docstring
        """ """
        structure_type = obj
        return self.request.route_url("structure_types.view", uuid=structure_type.uuid)


class UnitRef(ObjectRef):
    """
    Custom schema type for a :class:`~wuttafarm.db.model.units.Unit`
    reference field.

    This is a subclass of
    :class:`~wuttaweb:wuttaweb.forms.schema.ObjectRef`.
    """

    @property
    def model_class(self):
        model = self.app.model
        return model.Unit

    def sort_query(self, query):
        return query.order_by(self.model_class.name)

    def get_object_url(self, unit):
        return self.request.route_url("units.view", uuid=unit.uuid)


class UsersType(colander.SchemaType):

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        return json.dumps(appstruct)

    def widget_maker(self, **kwargs):  # pylint: disable=empty-docstring
        """ """
        from wuttafarm.web.forms.widgets import UsersWidget

        return UsersWidget(self.request, **kwargs)


class AssetRefs(WuttaSet):
    """
    Schema type for Assets field (on a Log record)
    """

    def __init__(
        self, request, for_asset=None, is_group=None, is_location=None, **kwargs
    ):
        super().__init__(request, **kwargs)
        self.is_group = is_group
        self.is_location = is_location
        self.for_asset = for_asset

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        return {asset.uuid.hex for asset in appstruct}

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import AssetRefsWidget

        model = self.app.model
        session = Session()

        if "values" not in kwargs:
            query = session.query(model.Asset)
            if self.is_group is not None:
                query = query.join(model.GroupAsset)
            if self.is_location is not None:
                query = query.filter(model.Asset.is_location == self.is_location)
            if self.for_asset:
                query = query.filter(model.Asset.uuid != self.for_asset.uuid)
            query = query.order_by(model.Asset.asset_name)
            values = [(asset.uuid.hex, str(asset)) for asset in query]
            kwargs["values"] = values

        return AssetRefsWidget(self.request, **kwargs)


class QuantityRefs(colander.List):
    """
    Schema type for Quantities field (on a Log record)
    """

    def __init__(self, request):
        super().__init__()
        self.request = request
        self.config = self.request.wutta_config
        self.app = self.config.get_app()

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        quantities = []
        for qty in appstruct:

            quantity = {
                "uuid": qty.uuid.hex,
                "quantity_type": {
                    "drupal_id": qty.quantity_type_id,
                    "name": qty.quantity_type.name,
                },
                "measure": qty.measure_id,
                "value": qty.get_value_decimal(),
                "units": {
                    "uuid": qty.units.uuid.hex,
                    "name": qty.units.name,
                },
                "as_text": qty.render_as_text(self.config),
                # nb. always include this regardless of quantity type,
                # for sake of easier frontend logic
                "material_types": [],
            }

            if qty.quantity_type_id == "material":
                quantity["material_types"] = []
                for mtype in qty.material_types:
                    quantity["material_types"].append(
                        {
                            "uuid": mtype.uuid.hex,
                            "name": mtype.name,
                        }
                    )

            quantities.append(quantity)

        return quantities

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import QuantityRefsWidget

        return QuantityRefsWidget(self.request, **kwargs)


class OwnerRefs(WuttaSet):
    """
    Schema type for Owners field (on a Log record)
    """

    def serialize(self, node, appstruct):
        if not appstruct:
            return colander.null

        return {user.uuid for user in appstruct}

    def widget_maker(self, **kwargs):
        from wuttafarm.web.forms.widgets import OwnerRefsWidget

        return OwnerRefsWidget(self.request, **kwargs)


class Notes(colander.String):
    """
    Custom schema type for "note" fields.
    """

    def serialize(self, node, appstruct):
        """ """
        if not appstruct:
            return colander.null

        return super().serialize(node, appstruct)

    def widget_maker(self, **kwargs):
        """
        Construct a default widget for the field.

        :returns: Instance of
           :class:`~wuttaweb.forms.widgets.NotesWidget`.
        """
        return NotesWidget(**kwargs)
