# -*- coding: utf-8 -*-
# Copyright (C) 2023-2026 TU-Dresden (ZIH)
# ralf.klammer@tu-dresden.de
# moritz.wilhelm@tu-dresden.de

import logging

from flask import Blueprint, render_template, request, session, jsonify

from tgp_backend.project import Project
from tgp_backend.tgclient import TGclient

log = logging.getLogger(__name__)

publication_routes = Blueprint("publication", __name__)


class TGProjectHandler:
    def __init__(self, projectname, instance, action="upload"):
        self.project = Project(projectname)
        self.tg_project = self.project.get_tgp(instance)
        self.instance = instance
        self.action = action

    def _render_template(self, action="upload", **kwargs):
        return render_template(
            f"includes/{self.action}_form.html",
            project=self.project,
            tg_project=self.tg_project,
            instance=self.instance,
        )

    @property
    def proofed_collections(self):
        return session.get("proofed_collections", [])

    @proofed_collections.setter
    def proofed_collections(self, value):
        session["proofed_collections"] = value

    def save_session_id(self, session_id):
        self.tg_project.tg_session_id = session_id
        return self._render_template()

    def save_tg_project_id(self, tg_project_id, sessionid):
        self.tg_project.tg_project_id = tg_project_id
        return modal_manage_tg_projects(
            sessionid, self.instance, self.project.path
        )

    def delete_tg_project(self, tg_project_id):
        self.tg_project.delete_tg_project(tg_project_id)
        return self._render_template()

    def clear_tg_project(self, tg_project_id):
        self.tg_project.clear_tg_project(tg_project_id)
        return self._render_template()

    def create_tg_project(self, tg_projectname, sessionid=None):
        self.tg_project.create_tg_project(tg_projectname)
        if sessionid:
            return modal_manage_tg_projects(
                sessionid, self.instance, self.project.path
            )
        return self._render_template()

    def upload_collection(self, collection_name):
        self.tg_project.upload_collection_run(collection_name=collection_name)
        return self._render_template()

    def upload_other_files(self):
        self.tg_project.upload_other_files()
        return self._render_template()

    def publish_collection(self, collection_name, dry_run=True):
        self.tg_project.publish_collection(collection_name=collection_name)
        return self._render_template()


# +++TABS+++
# ***1. UPLOAD***
@publication_routes.route(
    "/tab-prepare-upload/<string:projectname>", methods=["GET"]
)
def tab_upload(projectname):
    project = Project(projectname)
    return render_template(
        "tabs/upload.html",
        project=project,
    )


# ***2. CHECK UPLOAD***
@publication_routes.route(
    "/tab-check-upload/<string:projectname>", methods=["GET"]
)
def tab_check_upload(projectname):
    project = Project(projectname)

    images = [
        {
            "filename": "01_title.png",
            "alt": "Confirm Title",
            "caption": "Confirm your project's title and short description",
            "icon": "bi-card-heading text-primary",
        },
        {
            "filename": "02_avatar.png",
            "alt": "Check Avatar Image",
            "caption": "Check that your avatar image looks correct.",
            "icon": "bi-person-circle text-secondary",
        },
        {
            "filename": "03_readme.png",
            "alt": "Check README.md",
            "caption": "Check your README.md at your landing page.",
            "icon": "bi-file-earmark-text text-success",
        },
        {
            "filename": "04_count_objects.png",
            "alt": "Check Number of Imported Objects",
            "caption": "Confirm the number of imported objects",
            "icon": "bi-123 text-info",
        },
        {
            "filename": "05_facets.png",
            "alt": "Check Facets and Metadata",
            "caption": "Ensure that all facets and metadata are displayed correctly.",
            "icon": "bi-ui-checks-grid text-warning",
        },
        {
            "filename": "06_transformation.png",
            "alt": "Check TEI to HTML Transformation",
            "caption": "Check that some of your TEI files are being correctly transformed into HTML.",
            "icon": "bi-filetype-html text-danger",
        },
        # {"filename": "", "alt": "", "caption": ""},
    ]

    return render_template(
        "tabs/check_upload.html",
        project=project,
        images=images,
    )


# ***3. PUBLICATION***
@publication_routes.route(
    "/tab-publication/<string:projectname>", methods=["GET"]
)
def tab_publication(projectname):
    project = Project(projectname)
    return render_template(
        "tabs/publication.html",
        project=project,
        proofed_collections=session.get("proofed_collections", []),
    )


# +++TextGrid+++
# ***SESSSION***
@publication_routes.route(
    "/save_session_id/<string:projectname>/<string:instance>/<string:action>",
    methods=["POST"],
)
def save_session_id(projectname, instance, action):
    return TGProjectHandler(projectname, instance, action).save_session_id(
        request.form.get("tg_auth_session_id")
    )


# ***PROJECTS***
@publication_routes.route(
    "/modal-manage-projects/<string:sessionid>/<string:instance>/<string:projectname>",
    methods=["POST"],
)
def modal_manage_tg_projects(sessionid, instance, projectname):
    tg_client = TGclient(sessionid, instance)
    project = Project(projectname)
    return render_template(
        "modal/manage_projects.html",
        tg_client=tg_client,
        instance=instance,
        projectname=projectname,
        sessionid=sessionid,
        current_tg_project_id=project.main_config.get_tg_project_id(instance),
    )


@publication_routes.route(
    "/create-tg-project/<string:projectname>/<string:instance>/<string:action>",
    methods=["POST"],
)
@publication_routes.route(
    "/create-tg-project/<string:projectname>/<string:instance>/<string:action>/<string:sessionid>",
    methods=["POST"],
)
def create_tg_project(projectname, instance, action, sessionid=None):
    return TGProjectHandler(projectname, instance, action).create_tg_project(
        request.form.get("tg_projectname"), sessionid
    )


@publication_routes.route(
    "/save-tg-project_id/<string:projectname>/<string:instance>/<string:tg_project_id>/<string:action>/<string:sessionid>",
    methods=["POST"],
)
def save_tg_project_id(
    projectname,
    instance,
    tg_project_id,
    action,
    sessionid,
):
    return TGProjectHandler(projectname, instance, action).save_tg_project_id(
        tg_project_id, sessionid
    )


@publication_routes.route(
    "/clear-tg-project/<string:projectname>/<string:instance>/<string:tg_project_id>/<string:action>",
    methods=["POST"],
)
def clear_tg_project(projectname, instance, tg_project_id, action):
    return TGProjectHandler(projectname, instance, action).clear_tg_project(
        tg_project_id
    )


@publication_routes.route(
    "/delete-tg-project_id/<string:projectname>/<string:instance>/<string:tg_project_id>/<string:action>",
    methods=["POST"],
)
def delete_tg_project_id(projectname, instance, tg_project_id, action):
    return TGProjectHandler(projectname, instance, action).delete_tg_project(
        tg_project_id
    )


# +++UPLOAD+++
# ***COLLECTION***
@publication_routes.route(
    "/upload-collection-manage/<string:projectname>/<string:collection>/<string:instance>",
    methods=["POST"],
)
def upload_collection_manage(projectname, collection, instance):
    project = Project(projectname)
    return render_template(
        "modal/manage_upload.html",
        instance=instance,
        collection=collection,
        projectname=projectname,
        initial_status=project.project_handler.collection_upload_status_get(
            collection
        ),
    )


@publication_routes.route(
    "/upload-collection-start/<string:projectname>/<string:collection>/<string:instance>",
    methods=["POST"],
)
def upload_collection_start(projectname, collection, instance):
    TGProjectHandler(projectname, instance).tg_project.upload_collection_run(
        collection_name=collection
    )
    return jsonify("OK")


@publication_routes.route(
    "/upload-collection-status/<string:projectname>/<string:collection>/<string:instance>",
    methods=["GET"],
)
def upload_collection_status(projectname, collection, instance):
    project = Project(projectname)
    return jsonify(
        project.project_handler.collection_upload_status_get(collection)
    )


# ***OTHER FILES***
@publication_routes.route(
    "/upload-other-files-manage/<string:projectname>/<string:instance>",
    methods=["POST"],
)
def upload_other_files_manage(projectname, instance):
    project = Project(projectname)
    return render_template(
        "modal/manage_upload.html",
        instance=instance,
        projectname=projectname,
        initial_status=project.project_handler.other_files_upload_status_get(),
    )


@publication_routes.route(
    "/upload-other-files-start/<string:projectname>/<string:instance>",
    methods=["POST"],
)
def upload_other_files_start(projectname, instance):
    TGProjectHandler(projectname, instance).tg_project.upload_other_files_run()
    return jsonify("OK")


@publication_routes.route(
    "/upload-other-files-status/<string:projectname>/<string:instance>",
    methods=["GET"],
)
def upload_other_files_status(projectname, instance):
    project = Project(projectname)
    return jsonify(project.project_handler.other_files_upload_status_get())


# +++PUBLICATION+++
# ***COLLECTION***
@publication_routes.route(
    "/publish-collection-manage/<string:projectname>/<string:collection>/<string:instance>",
    methods=["POST"],
)
def publish_collection_manage(projectname, collection, instance):
    project = Project(projectname)
    return render_template(
        "modal/manage_publication.html",
        instance=instance,
        collection=collection,
        projectname=projectname,
        initial_status=project.project_handler.collection_publication_status_get(
            collection
        ),
    )


@publication_routes.route(
    "/publish-collection-start/<string:projectname>/<string:instance>/<string:collection>/<string:dry_run>",
    methods=["POST"],
)
def publish_collection_start(projectname, instance, collection, dry_run=True):
    TGProjectHandler(projectname, instance).tg_project.publish_collection_run(
        collection, dry_run=dry_run
    )
    return jsonify("OK")


@publication_routes.route(
    "/publish-collection-status/<string:projectname>/<string:instance>/<string:collection>",
    methods=["GET"],
)
def publish_collection_status(projectname, instance, collection):
    project = Project(projectname)
    return jsonify(
        project.project_handler.collection_publication_status_get(collection)
    )


# ***OTHER FILES***
@publication_routes.route(
    "/publish-other-files-manage/<string:projectname>/<string:instance>",
    methods=["POST"],
)
def publish_other_files_manage(projectname, instance):
    project = Project(projectname)
    return render_template(
        "modal/manage_publication.html",
        instance=instance,
        projectname=projectname,
        initial_status=project.project_handler.other_files_publication_status_get(),
    )


@publication_routes.route(
    "/publish-other-files-start/<string:projectname>/<string:instance>/<string:dry_run>",
    methods=["POST"],
)
def publish_other_files_start(projectname, instance, dry_run=True):
    TGProjectHandler(projectname, instance).tg_project.publish_other_files_run(
        dry_run=dry_run
    )
    return jsonify("OK")


@publication_routes.route(
    "/publish-other-files-status/<string:projectname>/<string:instance>",
    methods=["GET"],
)
def publish_other_files_status(projectname, instance):
    project = Project(projectname)
    return jsonify(
        project.project_handler.other_files_publication_status_get()
    )
