#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: <NAME>
# License: MIT


import json
import flask

from typing import Dict
from typing import List
from typing import Any

from animewatchlist.utilities import check_for_data_folder

from animewatchlist.values import FilePaths
from animewatchlist.values import Defaults


def find_anime_seaons_count(anime_id: int) -> str:
    """
    Returns anime seasons count.

    :param anime_id: The anime id to get count
    :return: Anime seasons count
    """

    # Get animes data from file.
    animes = get_animes_data()

    # Count of anime seasons
    count = 1
    count += len(list(filter(lambda anime: anime.get('belongToById') == anime_id, animes)))

    # Return a formatted string for seasons count in Turkish.
    return f'{count if count > 1 else "Tek"} Sezon'

def create_new_anime_from_form(anime_id: int, process_type: str) -> Dict[str, Any]:
    """
    Takes the get request contents and creates a dict object.
    Then configures by process_type.

    :param anime_id: New anime ID
    :param process_type: Creates an anime dict object by 'new', 'new_seaons' or 'edit'
    :return: Anime dict detail object
    """

    animes = get_animes_data()

    name = flask.request.form['anime-name-input'].strip()
    english_name = flask.request.form['anime-english-name-input'].strip() if flask.request.form['anime-english-name-input'] else None

    link = flask.request.form['anime-turkanime-link-input'].strip()
    image = flask.request.form['anime-image-link-input'].strip()

    watched = True if flask.request.form['anime-watched-input'] == 'true' else False
    favorite = True if flask.request.form['anime-favorite-input'] == 'true' else False
    
    categories = []
    if flask.request.form['anime-categories-input']:
        categories = sorted([category.title().strip() for category in flask.request.form['anime-categories-input'].split(',')])

    summary = flask.request.form['anime-summary-input'].strip()
    release_date = flask.request.form['anime-release-date-input']

    process_type = process_type.lower()
    new_anime = {
        'id': None,
        'name': name,
        'englishName': english_name,
        'watched': watched,
        'link': link,
        'image': image,
        'belongToById': None,
        'categories': categories,
        'summary': summary,
        'releaseDate': release_date,
        'favorite': favorite
    }

    if process_type == 'new':
        new_anime['id'] = anime_id
    elif process_type == 'new_season':
        new_anime['id'] = animes[-1].get('id') + 1
        new_anime['belongToById'] = anime_id
    elif process_type == 'edit':
        for anime in animes:
            if anime.get('id') == anime_id:
                new_anime['id'] = anime_id
                new_anime['belongToById'] = anime.get('belongToById')

    return new_anime


def sort_animes_by(animes: List[Dict[str, Any]], by: str = 'name') -> List[Dict[str, Any]]:
    """
    Sorts animes by key.

    :param animes: Animes in list/tuple
    :param by: Sort key (default: 'name')
    :return: Sorted animes dict object
    """

    try:
        animes = sorted(animes, key=lambda x: x[by])
    except KeyError:
        pass
    return animes


def get_animes_data() -> List[Dict[str, Any]]:
    """
    Returns the data of recorded animes.

    :return: Data of animes
    """

    # Call the function that checks if the data folder exists.
    check_for_data_folder()

    # Try to scrape the anime's file and return it.
    # If the file cannot be found, create it with the default value. 
    try:
        with open(file=FilePaths.ANIMES_FILE, mode='r', encoding='utf-8') as f:
            animes = json.load(f)
            return animes
    except FileNotFoundError:
        write_default_animes_data()
        return get_animes_data()


def write_default_animes_data() -> None:
    """
    Creates the default animes data file.
    """

    # Call the function that checks if the data folder exists.
    check_for_data_folder()

    # Writes default data.
    with open(file=FilePaths.ANIMES_FILE, mode='w', encoding='utf-8') as f:
        json.dump(Defaults.ANIMES_DATA, f, ensure_ascii=False)


def is_this_anime_exists(link: str, image: str) -> bool:
    """
    Checks is the anime exists or not with its TurkAnime.net link and image link.

    :param link: TurkAnime.net anime link
    :param image: TurkAnime.net image link
    :return: True/False by exists
    """

    animes = get_animes_data()

    for anime in animes:
        if anime.get('link') == link or anime.get('image') == image:
            return True

    return False


def get_anime_details_by(key: str, value: Any) -> List[Dict[str, Any]]:
    """
    Returns a specific key value in animes.

    :param key: Dict key
    :param value: Dict key value
    :return: Anime by key
    """

    animes = get_animes_data()

    for anime in animes:
        if anime.get(key):
            if str(anime.get(key)).lower() == str(value).lower():
                return anime

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: <NAME>
# License: MIT


import json
import flask

from typing import Dict
from typing import List
from typing import Any

from animewatchlist.utilities import check_for_data_folder

from animewatchlist.values import FilePaths
from animewatchlist.values import Defaults


def find_anime_seaons_count(anime_id: int) -> str:
    """
    Returns anime seasons count.

    :param anime_id: The anime id to get count
    :return: Anime seasons count
    """

    # Get animes data from file.
    animes = get_animes_data()

    # Count of anime seasons
    count = 1
    count += len(list(filter(lambda anime: anime.get('belongToById') == anime_id, animes)))

    # Return a formatted string for seasons count in Turkish.
    return f'{count if count > 1 else "Tek"} Sezon'

def create_new_anime_from_form(anime_id: int, process_type: str) -> Dict[str, Any]:
    """
    Takes the get request contents and creates a dict object.
    Then configures by process_type.

    :param anime_id: New anime ID
    :param process_type: Creates an anime dict object by 'new', 'new_seaons' or 'edit'
    :return: Anime dict detail object
    """

    animes = get_animes_data()

    name = flask.request.form['anime-name-input'].strip()
    english_name = flask.request.form['anime-english-name-input'].strip() if flask.request.form['anime-english-name-input'] else None

    link = flask.request.form['anime-turkanime-link-input'].strip()
    image = flask.request.form['anime-image-link-input'].strip()

    watched = True if flask.request.form['anime-watched-input'] == 'true' else False
    favorite = True if flask.request.form['anime-favorite-input'] == 'true' else False
    
    categories = []
    if flask.request.form['anime-categories-input']:
        categories = sorted([category.title().strip() for category in flask.request.form['anime-categories-input'].split(',')])

    summary = flask.request.form['anime-summary-input'].strip()
    release_date = flask.request.form['anime-release-date-input']

    process_type = process_type.lower()
    new_anime = {
        'id': None,
        'name': name,
        'englishName': english_name,
        'watched': watched,
        'link': link,
        'image': image,
        'belongToById': None,
        'categories': categories,
        'summary': summary,
        'releaseDate': release_date,
        'favorite': favorite
    }

    if process_type == 'new':
        new_anime['id'] = anime_id
    elif process_type == 'new_season':
        new_anime['id'] = animes[-1].get('id') + 1
        new_anime['belongToById'] = anime_id
    elif process_type == 'edit':
        for anime in animes:
            if anime.get('id') == anime_id:
                new_anime['id'] = anime_id
                new_anime['belongToById'] = anime.get('belongToById')

    return new_anime


def sort_animes_by(animes: List[Dict[str, Any]], by: str = 'name') -> List[Dict[str, Any]]:
    """
    Sorts animes by key.

    :param animes: Animes in list/tuple
    :param by: Sort key (default: 'name')
    :return: Sorted animes dict object
    """

    try:
        animes = sorted(animes, key=lambda x: x[by])
    except KeyError:
        pass
    return animes


def get_animes_data() -> List[Dict[str, Any]]:
    """
    Returns the data of recorded animes.

    :return: Data of animes
    """

    # Call the function that checks if the data folder exists.
    check_for_data_folder()

    # Try to scrape the anime's file and return it.
    # If the file cannot be found, create it with the default value. 
    try:
        with open(file=FilePaths.ANIMES_FILE, mode='r', encoding='utf-8') as f:
            animes = json.load(f)
            return animes
    except FileNotFoundError:
        write_default_animes_data()
        return get_animes_data()


def write_default_animes_data() -> None:
    """
    Creates the default animes data file.
    """

    # Call the function that checks if the data folder exists.
    check_for_data_folder()

    # Writes default data.
    with open(file=FilePaths.ANIMES_FILE, mode='w', encoding='utf-8') as f:
        json.dump(Defaults.ANIMES_DATA, f, ensure_ascii=False)


def is_this_anime_exists(link: str, image: str) -> bool:
    """
    Checks is the anime exists or not with its TurkAnime.net link and image link.

    :param link: TurkAnime.net anime link
    :param image: TurkAnime.net image link
    :return: True/False by exists
    """

    animes = get_animes_data()

    for anime in animes:
        if anime.get('link') == link or anime.get('image') == image:
            return True

    return False


def get_anime_details_by(key: str, value: Any) -> List[Dict[str, Any]]:
    """
    Returns a specific key value in animes.

    :param key: Dict key
    :param value: Dict key value
    :return: Anime by key
    """

    animes = get_animes_data()

    for anime in animes:
        if anime.get(key):
            if str(anime.get(key)).lower() == str(value).lower():
                return anime

#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: <NAME> # License: MIT Returns anime seasons count.      :param anime_id: The anime id to get count     :return: Anime seasons count # Get animes data from file. # Count of anime seasons # Return a formatted string for seasons count in Turkish. Takes the get request contents and creates a dict object.     Then configures by process_type.      :param anime_id: New anime ID     :param process_type: Creates an anime dict object by 'new', 'new_seaons' or 'edit'     :return: Anime dict detail object Sorts animes by key.      :param animes: Animes in list/tuple     :param by: Sort key (default: 'name')     :return: Sorted animes dict object Returns the data of recorded animes.      :return: Data of animes # Call the function that checks if the data folder exists. # Try to scrape the anime's file and return it. # If the file cannot be found, create it with the default value. Creates the default animes data file. # Call the function that checks if the data folder exists. # Writes default data. Checks is the anime exists or not with its TurkAnime.net link and image link.      :param link: TurkAnime.net anime link     :param image: TurkAnime.net image link     :return: True/False by exists Returns a specific key value in animes.      :param key: Dict key     :param value: Dict key value     :return: Anime by key