# -*- coding: UTF-8 -*-

# Copyright (C) 2020 Avencall
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from flask import url_for
from flask_restful import reqparse, fields
from xivo_dao.alchemy.labels import Labels
from xivo_dao.helpers import errors

from xivo_confd.authentication.confd_auth import required_acl
from xivo_confd.helpers.restful import ListResource, ItemResource, Strict

label_fields = {
    'id': fields.Integer,
    'display_name': fields.String,
    'description': fields.String,
    'users_count': fields.Integer
}

parser = reqparse.RequestParser()
parser.add_argument('display_name', type=Strict(str), required=True)
parser.add_argument('description', type=Strict(str), store_missing=False)


class LabelList(ListResource):
    model = Labels
    fields = label_fields
    parser = parser

    def build_headers(self, label):
        return {'Location': url_for('static', id=label.id, _external=True, filename=[])}

    @required_acl('confd.labels.read')
    def get(self):
        return super(LabelList, self).get()

    @required_acl('confd.labels.create')
    def post(self):
        return super(LabelList, self).post()


class LabelItem(ItemResource):
    model = Labels
    fields = label_fields
    parser = parser

    @required_acl('confd.labels.{id}.read')
    def get(self, id):
        return super(LabelItem, self).get(id)

    @required_acl('confd.labels.{id}.delete')
    def delete(self, id):
        label = self.service.get(id)
        if label is None:
            raise errors.not_found('Label', id=id)
        return super(LabelItem, self).delete(id)

    @required_acl('confd.labels.{id}.update')
    def put(self, id):
        label = self.service.get(id)
        if label is None:
            raise errors.not_found('Label', id=id)
        return super(LabelItem, self).put(id)
