# -*- 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/>.
#
################################################################################
"""
Master view for Farm Plants
"""

import datetime

import colander

from wuttaweb.forms.schema import WuttaDateTime
from wuttaweb.forms.widgets import WuttaDateTimeWidget

from wuttafarm.web.views.farmos.master import TaxonomyMasterView
from wuttafarm.web.views.farmos import FarmOSMasterView
from wuttafarm.web.forms.schema import UsersType, StructureType, FarmOSPlantTypes
from wuttafarm.web.forms.widgets import ImageWidget


class PlantTypeView(TaxonomyMasterView):
    """
    Master view for Plant Types in farmOS.
    """

    model_name = "farmos_plant_type"
    model_title = "farmOS Plant Type"
    model_title_plural = "farmOS Plant Types"

    route_prefix = "farmos_plant_types"
    url_prefix = "/farmOS/plant-types"

    farmos_taxonomy_type = "plant_type"
    farmos_refurl_path = "/admin/structure/taxonomy/manage/plant_type/overview"

    def get_xref_buttons(self, plant_type):
        buttons = super().get_xref_buttons(plant_type)
        model = self.app.model
        session = self.Session()

        if wf_plant_type := (
            session.query(model.PlantType)
            .filter(model.PlantType.farmos_uuid == plant_type["uuid"])
            .first()
        ):
            buttons.append(
                self.make_button(
                    f"View {self.app.get_title()} record",
                    primary=True,
                    url=self.request.route_url(
                        "plant_types.view", uuid=wf_plant_type.uuid
                    ),
                    icon_left="eye",
                )
            )

        return buttons


class PlantAssetView(FarmOSMasterView):
    """
    Master view for farmOS Plant Assets
    """

    model_name = "farmos_plant_assets"
    model_title = "farmOS Plant Asset"
    model_title_plural = "farmOS Plant Assets"

    route_prefix = "farmos_plant_assets"
    url_prefix = "/farmOS/assets/plant"

    farmos_refurl_path = "/assets/plant"

    grid_columns = [
        "name",
        "archived",
    ]

    sort_defaults = "name"

    form_fields = [
        "name",
        "plant_types",
        "archived",
        "owners",
        "location",
        "notes",
        "raw_image_url",
        "large_image_url",
        "thumbnail_image_url",
        "image",
    ]

    def get_grid_data(self, columns=None, session=None):
        result = self.farmos_client.asset.get("plant")
        return [self.normalize_plant(a) for a in result["data"]]

    def configure_grid(self, grid):
        g = grid
        super().configure_grid(g)

        # name
        g.set_link("name")
        g.set_searchable("name")

        # archived
        g.set_renderer("archived", "boolean")

    def get_instance(self):

        plant = self.farmos_client.resource.get_id(
            "asset", "plant", self.request.matchdict["uuid"]
        )
        self.raw_json = plant

        # instance data
        data = self.normalize_plant(plant["data"])

        if relationships := plant["data"].get("relationships"):

            # add plant types
            if plant_type := relationships.get("plant_type"):
                if plant_type["data"]:
                    data["plant_types"] = []
                    for plant_type in plant_type["data"]:
                        plant_type = self.farmos_client.resource.get_id(
                            "taxonomy_term", "plant_type", plant_type["id"]
                        )
                        data["plant_types"].append(
                            {
                                "uuid": plant_type["data"]["id"],
                                "name": plant_type["data"]["attributes"]["name"],
                            }
                        )

            # add location
            if location := relationships.get("location"):
                if location["data"]:
                    location = self.farmos_client.resource.get_id(
                        "asset", "structure", location["data"][0]["id"]
                    )
                    data["location"] = {
                        "uuid": location["data"]["id"],
                        "name": location["data"]["attributes"]["name"],
                    }

            # add owners
            if owner := relationships.get("owner"):
                data["owners"] = []
                for owner_data in owner["data"]:
                    owner = self.farmos_client.resource.get_id(
                        "user", "user", owner_data["id"]
                    )
                    data["owners"].append(
                        {
                            "uuid": owner["data"]["id"],
                            "display_name": owner["data"]["attributes"]["display_name"],
                        }
                    )

            # add image urls
            if image := relationships.get("image"):
                if image["data"]:
                    image = self.farmos_client.resource.get_id(
                        "file", "file", image["data"][0]["id"]
                    )
                    data["raw_image_url"] = self.app.get_farmos_url(
                        image["data"]["attributes"]["uri"]["url"]
                    )
                    # nb. other styles available:  medium, wide
                    data["large_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["large"]
                    data["thumbnail_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["thumbnail"]

        return data

    def get_instance_title(self, plant):
        return plant["name"]

    def normalize_plant(self, plant):

        if notes := plant["attributes"]["notes"]:
            notes = notes["value"]

        if self.farmos_4x:
            archived = plant["attributes"]["archived"]
        else:
            archived = plant["attributes"]["status"] == "archived"

        return {
            "uuid": plant["id"],
            "drupal_id": plant["attributes"]["drupal_internal__id"],
            "name": plant["attributes"]["name"],
            "location": colander.null,  # TODO
            "archived": archived,
            "notes": notes or colander.null,
        }

    def configure_form(self, form):
        f = form
        super().configure_form(f)
        plant = f.model_instance

        # plant_types
        f.set_node("plant_types", FarmOSPlantTypes(self.request))

        # location
        f.set_node("location", StructureType(self.request))

        # owners
        f.set_node("owners", UsersType(self.request))

        # notes
        f.set_widget("notes", "notes")

        # archived
        f.set_node("archived", colander.Boolean())

        # image
        if url := plant.get("large_image_url"):
            f.set_widget("image", ImageWidget("plant image"))
            f.set_default("image", url)

    def get_xref_buttons(self, plant):
        model = self.app.model
        session = self.Session()

        buttons = [
            self.make_button(
                "View in farmOS",
                primary=True,
                url=self.app.get_farmos_url(f"/asset/{plant['drupal_id']}"),
                target="_blank",
                icon_left="external-link-alt",
            ),
        ]

        if wf_plant := (
            session.query(model.Asset)
            .filter(model.Asset.farmos_uuid == plant["uuid"])
            .first()
        ):
            buttons.append(
                self.make_button(
                    f"View {self.app.get_title()} record",
                    primary=True,
                    url=self.request.route_url("plant_assets.view", uuid=wf_plant.uuid),
                    icon_left="eye",
                )
            )

        return buttons


def defaults(config, **kwargs):
    base = globals()

    PlantTypeView = kwargs.get("PlantTypeView", base["PlantTypeView"])
    PlantTypeView.defaults(config)

    PlantAssetView = kwargs.get("PlantAssetView", base["PlantAssetView"])
    PlantAssetView.defaults(config)


def includeme(config):
    defaults(config)
