# -*- coding: utf-8 -*-
# Copyright 2023 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""API handlers for retrieving and summarizing links associated with features."""

from chromestatus_openapi.models import (
    FeatureLinksResponse,
    FeatureLinksSummaryResponse,
)

from framework import basehandlers, permissions
from internals.feature_links import (
    get_by_feature_id,
    get_feature_links_samples,
    get_feature_links_summary,
)


class FeatureLinksAPI(basehandlers.APIHandler):
    """FeatureLinksAPI will return the links and its information to the client."""

    def do_get(self, **kwargs):
        """Get links for a feature."""
        feature = self.get_specified_feature(**kwargs)
        update_stale_links = self.get_bool_arg('update_stale_links', True)
        data, has_stale_links = get_by_feature_id(
            feature.key.integer_id(), update_stale_links
        )
        return FeatureLinksResponse.from_dict(
            {'data': data, 'has_stale_links': has_stale_links}
        )


class FeatureLinksSummaryAPI(basehandlers.APIHandler):
    """FeatureLinksSummaryAPI will return summary of links to the client."""

    @permissions.require_admin_site
    def do_get(self, **kwargs):
        """Get summary of feature links."""
        return FeatureLinksSummaryResponse.from_dict(
            get_feature_links_summary()
        )


class FeatureLinksSamplesAPI(basehandlers.APIHandler):
    """FeatureLinksSamplesAPI will return sample links to the client."""

    @permissions.require_admin_site
    def do_get(self, **kwargs):
        """Get sample feature links."""
        domain = self.request.args.get('domain', None)
        type = self.request.args.get('type', None)
        is_error = self.get_bool_arg('is_error', None)
        if domain:
            return get_feature_links_samples(domain, type, is_error)
        return []
