'''
    Copyright (C) 2019 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    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, see <http://www.gnu.org/licenses/>.
'''
import connexion

from ..database.Model import User, Device, db
from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound


def devices_get(name=None, order_by=None, offset=None, limit=None):
    query = None

    user = User.loggedin_user()
    if user is None:
        raise MapserviceUnauthorized

    query = Device.query.filter_by(owner=user)
    if name is not None:
        query = query.filter(Device.name.like('%{}%'.format(name)))

    result = []
    for device in query.offset(offset).limit(limit):
        result.append(device.to_dict())
    return result


def devices_get_by_id(id):
    user = User.loggedin_user()
    if user is None:
        raise MapserviceUnauthorized

    device = Device.query.filter_by(owner=user).filter_by(id=id).all()
    if len(device) != 1:
        raise MapserviceNotFound
    return device[0].to_dict()


def devices_create(device_creation):
    user = User.loggedin_user()
    if user is None:
        raise MapserviceUnauthorized

    comment = ""
    if device_creation.comment:
        comment = device_creation.comment

    device = Device(
        name=device_creation.name,
        owner=user,
        sensor_depth=device_creation.sensor_depth,
        comment=comment
    )
    db.session.add(device)
    db.session.commit()
    return device.to_dict()


def devices_device_delete(id):
    user = User.loggedin_user()
    if user is None:
        raise MapserviceUnauthorized

    if not Device.query.filter_by(owner=user).filter_by(id=id).delete():
        raise MapserviceBadRequest(
            detail="Could not delete device with id {}".format(id)
        )
    db.session.commit()

    query = Device.query.filter_by(owner=user)
    result = []
    for device in query:
        result.append(device.to_dict())
    return result
