# -*- 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/>.
#
################################################################################
"""
Asset handler
"""

from wuttjamaican.app import GenericHandler


class AssetHandler(GenericHandler):
    """
    Base class and default implementation for the asset
    :term:`handler`.
    """

    def get_groups(self, asset):
        model = self.app.model
        session = self.app.get_session(asset)

        grplog = (
            session.query(model.Log)
            .join(model.LogAsset)
            .filter(model.LogAsset.asset == asset)
            .filter(model.Log.is_group_assignment == True)
            .order_by(model.Log.timestamp.desc())
            .first()
        )
        if grplog:
            return grplog.groups
        return []

    def get_locations(self, asset):
        model = self.app.model
        session = self.app.get_session(asset)

        loclog = (
            session.query(model.Log)
            .join(model.LogAsset)
            .filter(model.LogAsset.asset == asset)
            .filter(model.Log.is_movement == True)
            .order_by(model.Log.timestamp.desc())
            .first()
        )
        if loclog:
            return loclog.locations
        return []
