# -*- 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 Assets
"""

from collections import OrderedDict

from wuttaweb.forms.schema import WuttaDictEnum
from wuttaweb.db import Session

from wuttafarm.web.views import WuttaFarmMasterView
from wuttafarm.db.model import Asset
from wuttafarm.web.forms.schema import AssetParentRefs
from wuttafarm.web.forms.widgets import ImageWidget


def get_asset_type_enum(config):
    app = config.get_app()
    model = app.model
    session = Session()
    asset_types = OrderedDict()
    query = session.query(model.AssetType).order_by(model.AssetType.name)
    for asset_type in query:
        asset_types[asset_type.drupal_id] = asset_type.name
    return asset_types


class AssetView(WuttaFarmMasterView):
    """
    Master view for Assets
    """

    model_class = Asset
    route_prefix = "assets"
    url_prefix = "/assets"

    farmos_refurl_path = "/assets"

    viewable = False
    creatable = False
    editable = False
    deletable = False
    model_is_versioned = False

    grid_columns = [
        "thumbnail",
        "drupal_id",
        "asset_name",
        "asset_type",
        "parents",
        "archived",
    ]

    sort_defaults = "asset_name"

    filter_defaults = {
        "asset_name": {"active": True, "verb": "contains"},
        "archived": {"active": True, "verb": "is_false"},
    }

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

        # thumbnail
        g.set_renderer("thumbnail", self.render_grid_thumbnail)
        g.set_label("thumbnail", "", column_only=True)
        g.set_centered("thumbnail")

        # drupal_id
        g.set_label("drupal_id", "ID", column_only=True)

        # asset_name
        g.set_link("asset_name")

        # asset_type
        g.set_enum("asset_type", get_asset_type_enum(self.config))

        # parents
        g.set_renderer("parents", self.render_parents_for_grid)

        # view action links to final asset record
        def asset_url(asset, i):
            return self.request.route_url(
                f"{asset.asset_type}_assets.view", uuid=asset.uuid
            )

        g.add_action("view", icon="eye", url=asset_url)

    def render_parents_for_grid(self, asset, field, value):
        parents = [str(p.parent) for p in asset._parents]
        return ", ".join(parents)

    def grid_row_class(self, asset, data, i):
        """ """
        if asset.archived:
            return "has-background-warning"
        return None


class AssetTypeMasterView(WuttaFarmMasterView):
    """
    Base class for "Asset Type" master views.

    A bit of a misnmer perhaps, this is *not* for the actual AssetType
    model, but rather the "secondary" types, e.g.  AnimalType,
    LandType etc.
    """


class AssetMasterView(WuttaFarmMasterView):
    """
    Base class for Asset master views
    """

    sort_defaults = "asset_name"

    filter_defaults = {
        "asset_name": {"active": True, "verb": "contains"},
        "archived": {"active": True, "verb": "is_false"},
    }

    def get_fallback_templates(self, template):
        templates = super().get_fallback_templates(template)

        if self.viewing:
            templates.insert(0, "/assets/master/view.mako")

        return templates

    def get_query(self, session=None):
        """ """
        model = self.app.model
        model_class = self.get_model_class()
        session = session or self.Session()
        return session.query(model_class).join(model.Asset)

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

        # thumbnail
        g.set_renderer("thumbnail", self.render_grid_thumbnail)
        g.set_label("thumbnail", "", column_only=True)
        g.set_centered("thumbnail")

        # drupal_id
        g.set_label("drupal_id", "ID", column_only=True)
        g.set_sorter("drupal_id", model.Asset.drupal_id)
        g.set_filter("drupal_id", model.Asset.drupal_id)

        # asset_name
        g.set_link("asset_name")
        g.set_sorter("asset_name", model.Asset.asset_name)
        g.set_filter("asset_name", model.Asset.asset_name)

        # parents
        g.set_renderer("parents", self.render_parents_for_grid)

        # archived
        g.set_renderer("archived", "boolean")
        g.set_sorter("archived", model.Asset.archived)
        g.set_filter("archived", model.Asset.archived)

    def render_parents_for_grid(self, asset, field, value):
        parents = [str(p.parent) for p in asset.asset._parents]
        return ", ".join(parents)

    def grid_row_class(self, asset, data, i):
        """ """
        if asset.archived:
            return "has-background-warning"
        return None

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

        # asset_type
        if self.creating:
            f.remove("asset_type")
        else:
            f.set_node(
                "asset_type",
                WuttaDictEnum(self.request, get_asset_type_enum(self.config)),
            )
            f.set_readonly("asset_type")

        # parents
        if self.creating or self.editing:
            f.remove("parents")  # TODO: add support for this
        else:
            f.set_node("parents", AssetParentRefs(self.request))
            f.set_default("parents", [p.parent_uuid for p in asset.asset._parents])

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

        # thumbnail_url
        if self.creating or self.editing:
            f.remove("thumbnail_url")

        # image_url
        if self.creating or self.editing:
            f.remove("image_url")

        # thumbnail
        if self.creating or self.editing:
            f.remove("thumbnail")
        elif asset.thumbnail_url:
            f.set_widget("thumbnail", ImageWidget("animal thumbnail"))
            f.set_default("thumbnail", asset.thumbnail_url)

        # image
        if self.creating or self.editing:
            f.remove("image")
        elif asset.image_url:
            f.set_widget("image", ImageWidget("animal image"))
            f.set_default("image", asset.image_url)

    def objectify(self, form):
        asset = super().objectify(form)

        if self.creating:
            model_class = self.get_model_class()
            asset.asset_type = model_class.__wutta_hint__["farmos_asset_type"]

        return asset

    def get_farmos_url(self, asset):
        return self.app.get_farmos_url(f"/asset/{asset.drupal_id}")

    def get_xref_buttons(self, asset):
        buttons = super().get_xref_buttons(asset)

        if asset.farmos_uuid:

            # TODO
            route = None
            if asset.asset_type == "animal":
                route = "farmos_animals.view"
            elif asset.asset_type == "group":
                route = "farmos_groups.view"
            elif asset.asset_type == "land":
                route = "farmos_land_assets.view"
            elif asset.asset_type == "structure":
                route = "farmos_structures.view"

            if route:
                buttons.append(
                    self.make_button(
                        "View farmOS record",
                        primary=True,
                        url=self.request.route_url(route, uuid=asset.farmos_uuid),
                        icon_left="eye",
                    )
                )

        return buttons


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

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


def includeme(config):
    defaults(config)
