# Standard Library
from pathlib import Path

# Pip
from anki_hsk_creator import api
from anki_hsk_creator.constants import DICTATION_TYPE, DICT_TYPE, PHRASES_TYPE
from anki_hsk_creator.utility import ProcessFile
from flask import (
    Blueprint,
    make_response,
    redirect,
    render_template,
    request,
    send_from_directory,
    url_for,
)

mainapp = Blueprint(
    "mainapp",
    __name__,
    template_folder="templates",
    url_prefix="/hskankicreator/app",
    static_folder="static",
)


@mainapp.route("/", methods=["GET"])
def app():
    """Main app entry pages"""
    return redirect(url_for("mainapp.file_list"))
    # return render_template("app.html")


@mainapp.route("/list", methods=["GET", "POST", "DELETE"])
@mainapp.route("/list/", methods=["GET", "POST", "DELETE"])
@mainapp.route("/list/<path:listing_path>", methods=["GET", "POST", "DELETE"])
def file_list(listing_path=""):
    """Path for file lister"""
    if request.method == "GET":
        listing_path = Path(listing_path)
        root_files = {file: [] for file in api.list_input_files()}
        level = root_files
        level_path = Path()
        for part in listing_path.parts:
            level_path = level_path / part
            level[level_path] = {file: [] for file in api.list_input_files(level_path)}
            level = level[level_path]

        if listing_path:
            file_data = api.analize_input_files(listing_path)
        else:
            file_data = api.analize_input_files(None)
        return render_template(
            "file_list.html",
            file_data=file_data,
            root_files=root_files,
            listing_path=listing_path,
        )
    if request.method == "POST":
        form = request.form.to_dict()
        listing_path = Path(listing_path)
        path = listing_path / form['name']
        if form['type'] == "folder":
            api.create_folder(path)
            return redirect(
                (url_for("mainapp.file_list", listing_path=path))
            )
        elif form['type'] == "file":
            process_file = ProcessFile(listing_path)
            if process_file.absolute_input_file.is_file():
                listing_path = listing_path.parent
            return redirect(
                (url_for("mainapp.create", listing_path=path))
            )


@mainapp.route("/download/<path:listing_path>", methods=["GET"])
def download(listing_path):
    """Download a file from  DATA_FOLDER / DOWNLOAD"""
    download_path = api.get_output_folder() / listing_path
    return send_from_directory(download_path.parent, download_path.name)


@mainapp.route("/resource/<path:listing_path>", methods=["GET"])
def resource(listing_path):
    """Gets a file from  DATA_FOLDER / RESOURCES"""
    download_path = api.get_resources_folder() / listing_path
    return send_from_directory(download_path.parent, download_path.name)


@mainapp.route("/create", methods=["GET", "POST"])
@mainapp.route("/create/", methods=["GET", "POST"])
@mainapp.route("/create/<path:listing_path>", methods=["GET", "POST"])
def create(listing_path=""):
    """Main text editor"""
    if request.method == "GET":
        if api.is_file(listing_path):
            text = api.read_input_file(listing_path)
        else:
            text = ""
        args = request.args.to_dict()
        deck_type = args.get("deck_type", "")
        language_id = args.get("language_id", "")
        if not deck_type and not language_id:
            state = "new"
        elif not deck_type or not language_id:
            state = "partial"
        else:
            state = "complete"
        # output_type = args.get("output_type", "")
        # if not deck_type or not language_id or not output_type:
        return render_template(
            "create.html",
            data={
                "text": text,
                "deck_type": deck_type,
                "language_id": language_id,
                "state": state,
            },
        )
    else:
        listing_path = Path(listing_path)
        form = request.form.to_dict()
        args = request.args.to_dict()
        process_file = api.create_input_file(
            listing_path.name.split(".")[0],
            "." + args["deck_type"],
            form["text"],
            listing_path.parent,
        )
        if args["deck_type"] in DICT_TYPE:
            api.pre_process_a_dictionary_file(process_file, args["language_id"])
            return redirect(
                url_for(
                    "mainapp.process",
                    listing_path=process_file.relative_dictionary_resource_file,
                    language_id=args["language_id"],
                ),
                code=303,
            )
        elif args["deck_type"] in PHRASES_TYPE:
            final_file = api.process_a_phrases_file(process_file, args["language_id"])
            response = make_response(
                send_from_directory(final_file.parent, final_file.name)
            )
            response.set_cookie("download_started", "true", max_age=10)
            return response
        elif args["deck_type"] in DICTATION_TYPE:
            final_file = api.process_a_dictation_file(process_file, args["language_id"])
            response = make_response(
                send_from_directory(final_file.parent, final_file.name)
            )
            response.set_cookie("download_started", "true", max_age=10)
            return response


@mainapp.route("/process/<path:listing_path>", methods=["GET", "POST"])
def process(listing_path):
    """Post process tsv file"""
    listing_path = Path(listing_path)
    input_file = listing_path.parent
    input_file = input_file.parent / f"{input_file.name}.txt"
    process_file = ProcessFile(input_file)
    languages = process_file.available_dictionary_languages
    args = request.args.to_dict()
    language_id = args.get("language_id", listing_path.stem.split(".")[1])
    if request.method == "GET":
        if not language_id:
            state = "new"
            text = ""
        else:
            state = "complete"
            text = api.read_dictionary_file(process_file, language_id)
        output_type = args.get("output_type", "")
        return render_template(
            "process.html",
            languages=languages,
            data={
                "output_type": output_type,
                "language_id": language_id,
                "state": state,
                "text": text,
            },
        )
    elif request.method == "POST":
        form = request.form.to_dict()
        api.write_resource_file(process_file, language_id, form["text"])
        final_file = api.process_a_dictionary_file(process_file, language_id)
        response = make_response(
            send_from_directory(final_file.parent, final_file.name)
        )
        response.set_cookie("download_started", "true", max_age=10)
        return response
