from flask import Flask, jsonify, request
import requests
from uuid import uuid4
import uuid


class Book:
    def __init__(self, title, year, uuid_: uuid, author_id: uuid):
        if uuid_ is None:
            self.uuid_: uuid = uuid4()
        else:
            self.uuid_: uuid = uuid.UUID(uuid_)
        self.title: str = title
        self.year: int = year
        self.author_id: uuid = uuid.UUID(author_id)

    def to_dict(self):
        return {
            'title': self.title,
            'year': self.year,
            'author_id': self.author_id,
            'uuid': self.uuid_
        }

    def to_dict_for_authors(self):
        return {
            'title': self.title,
            'year': self.year,
            'uuid': self.uuid_
        }

    def to_dict_with_info(self, author: dict):
        return {
            'title': self.title,
            'year': self.year,
            'author_id': self.author_id,
            'author_info': author,
            'uuid': self.uuid_
        }


app = Flask(__name__)

books: list[Book] = [
    Book(title='Garden', year=1977, uuid_='89fa1e7a-7e88-445e-a4d8-6d4497ea8f19',
         author_id='997aa4c5-ebb2-4794-ba81-e742f9f1fa30'),
    Book(title='New York', year=1989, uuid_='0351ee11-f11b-4d83-b2c8-1075b0c357dc',
         author_id='694827e4-0f93-45a5-8f75-bad7ef2d21fe'),
    Book(title='The story of flowers', uuid_='dfc17619-7690-47aa-ae8e-6a5068f8ddec', year=1977,
         author_id='eb815350-c7b9-4446-8434-4c0640c21995'),
    Book(title='Little Rock', year=1990, uuid_='3fad0e6b-cefc-40dd-99c0-adc5ec0290d2',
         author_id='694827e4-0f93-45a5-8f75-bad7ef2d21fe'),
    Book(title='One Piece', year=1994, uuid_='cf0cf26e-c1c6-43ea-bf59-1f8edb180e41',
         author_id='694827e4-0f93-45a5-8f75-bad7ef2d21fe'),
    Book(title='Black clover', year=1940, uuid_='2ac3c734-21ad-4450-884d-7de1f5452b9d',
         author_id='eb815350-c7b9-4446-8434-4c0640c21995'),
]

authors_url = 'http://author_service:20001/'


def list_jsonify():
    return jsonify([book.to_dict() for book in books])


# получить список книг без подробной инфы об авторе
@app.route('/', methods=['GET'])
def get_all():
    return list_jsonify(), 200


# получение всех книг с информацией об авторе
@app.route('/full', methods=['GET'])
def get_all_full():
    authors: list[dict] = requests.get(authors_url).json()
    response = []
    for book in books:
        for author in authors:
            if book.author_id == uuid.UUID(author.get('uuid')):
                response.append(book.to_dict_with_info(author))

    return response, 200


# получение списка книг по идентификатору автора (для author_service)
@app.route('/by-author/<uuid:author_uuid>', methods=['GET'])
def get_by_author_id(author_uuid):
    return [book.to_dict_for_authors() for book in books if book.author_id == author_uuid], 200


# получение книги по идентификатору
@app.route('/<uuid:uuid_>', methods=['GET'])
def get_one(uuid_):
    for book in books:
        if book.uuid_ == uuid_:
            return book.to_dict(), 200

    return 'Книга с таким uuid не была найдена', 404


# получение книги по идентификатору с инфой об авторе
@app.route('/full/<uuid:uuid_>', methods=['GET'])
def get_one_full(uuid_):
    for book in books:
        if book.uuid_ == uuid_:
            response = requests.get(authors_url + str(book.author_id))
            return book.to_dict_with_info(response.json()), 200

    return 'Книга с таким uuid не была найдена', 404


# создание новой книги
@app.route('/', methods=['POST'])
def create():
    data = request.json
    title = data.get('title', None)
    year = data.get('year', None)
    author_id = data.get('author_id', None)
    checking = requests.get(authors_url + f'/check/{author_id}')
    print(checking)
    if checking.status_code == 200:
        new_book = Book(title, year, None, author_id)
        books.append(new_book)
        return get_one(new_book.uuid_)
    if checking.status_code == 404:
        return 'Автор с таким uuid не существует', 404

    return 'Неизвестная ошибка', 500


# изменение книги по идентификатору
@app.route('/<uuid:uuid_>', methods=['PUT'])
def update_by_id(uuid_):
    data = request.json
    new_title = data.get('title', None)
    new_year = data.get('year', None)

    for book in books:
        print(book.uuid_)

        if book.uuid_ == uuid_:
            if new_title is not None:
                book.title = new_title
            if new_year is not None:
                book.year = new_year
            return get_one(book.uuid_)

    return 'Книга с таким uuid не была найдена', 404


# удаление книги по идентификатору
@app.route('/<uuid:uuid_>', methods=['DELETE'])
def delete(uuid_):
    for book in books:
        if book.uuid_ == uuid_:
            books.remove(book)
            return 'Книга успешно удалена', 200

    return 'Книга с таким uuid не была найдена', 404


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=20002, debug=True)
