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


class Book:
    def __init__(self, title, year, author, uuid_: uuid, theme_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: str = author
        self.theme_id: uuid = uuid.UUID(theme_id)

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

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



app = Flask(__name__)

books: list[Book] = [
    Book(title='Mac', year=1977, author= 'Jane', uuid_='89fa1e7a-7e88-445e-a4d8-6d4497ea8f19',
         theme_id='997aa4c5-ebb2-4794-ba81-e742f9f1fa30'),
    Book(title='Portrait', year=1989, uuid_='0351ee11-f11b-4d83-b2c8-1075b0c357dc', author= 'Mark',
         theme_id='694827e4-0f93-45a5-8f75-bad7ef2d21fe'),
    Book(title='Chamomile', uuid_='dfc17619-7690-47aa-ae8e-6a5068f8ddec', year=1977, author= 'Laura',
         theme_id='997aa4c5-ebb2-4794-ba81-e742f9f1fa30')
]

themes_url = 'http://theme_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


# получение списка книг по идентификатору темы (для theme_service)
@app.route('/by-theme/<uuid:theme_uuid>', methods=['GET'])
def get_by_theme_id(theme_uuid):
    return [book.to_dict_for_themes() for book in books if book.theme_id == theme_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('/', methods=['POST'])
def create():
    data = request.json
    title = data.get('title', None)
    year = data.get('year', None)
    author = data.get('author', None)
    theme_id = data.get('theme_id', None)
    checking = requests.get(themes_url + f'/check/{theme_id}')
    print(checking)
    if checking.status_code == 200:
        new_book = Book(title, year,author, None, theme_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)
    new_author = data.get('author', 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
            if new_author is not None:
                book.author= new_author
            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)
