{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "\n",
    "pdf_uploader = widgets.FileUpload(description=\"Original pdfs\", accept=\".pdf\", multiple=True)\n",
    "tag_uploader = widgets.FileUpload(description=\"Tag image/pdf\", accept=\"image/*,.pdf\", multiple=False)\n",
    "output = widgets.Output()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@output.capture()\n",
    "def write_pdf(pdfs):\n",
    "    for pdf in pdfs:\n",
    "        print(f\"Loading {pdf.name}...\", end=\" \")\n",
    "        with open(pdf.name, \"wb\") as f:\n",
    "            f.write(pdf.content)\n",
    "        print(\"done\")\n",
    "            \n",
    "def write_original_pdf(counter):\n",
    "    if counter.get(\"new\") == 0:\n",
    "        return\n",
    "    write_pdf(pdf_uploader.value)\n",
    "def write_tag_pdf(counter):\n",
    "    if counter.get(\"new\") == 0:\n",
    "        return\n",
    "    write_pdf(tag_uploader.value)\n",
    "    \n",
    "pdf_uploader.observe(write_original_pdf, names=\"value\")\n",
    "tag_uploader.observe(write_tag_pdf, names=\"value\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def clear(_):\n",
    "    output.clear_output()\n",
    "    pdf_uploader._counter = 0\n",
    "    tag_uploader._counter = 0\n",
    "    pdf_uploader.value = tuple()\n",
    "    tag_uploader.value = tuple()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kwargs = dict(min=0.0, max=1.0, step=0.01)\n",
    "xpos = widgets.FloatSlider(value=0.5, description=\"$x$\", **kwargs)\n",
    "ypos = widgets.FloatSlider(value=0.5, description=\"$y$\", **kwargs)\n",
    "width = widgets.FloatSlider(value=0.7, description=\"width\", **kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@output.capture()\n",
    "def process(_):\n",
    "    import subprocess\n",
    "\n",
    "    if len(pdf_uploader.value) == 0:\n",
    "        print(\"Missing file to tag!\")\n",
    "        return\n",
    "\n",
    "    if len(tag_uploader.value) == 0:\n",
    "        print(\"Missing tag!\")\n",
    "        return\n",
    "\n",
    "    tag_name = tag_uploader.value[0].name\n",
    "    for pdf in pdf_uploader.value:\n",
    "        print(f\"Processing {pdf.name}...\", end=\" \")\n",
    "        result = subprocess.run(\n",
    "            [\n",
    "                \"./bin/generate_tag.sh\",\n",
    "                \"--multi\",\n",
    "                pdf.name,\n",
    "                \"--tag\",\n",
    "                tag_name,\n",
    "                \"-x\",\n",
    "                str(xpos.value),\n",
    "                \"-y\",\n",
    "                str(ypos.value),\n",
    "                \"-w\",\n",
    "                str(width.value),\n",
    "            ],\n",
    "            capture_output=True,\n",
    "            text=True,\n",
    "        )\n",
    "        if result.returncode != 0:\n",
    "            print(\"failed!\")\n",
    "            print(\"Check the following messages to know what's going on:\")\n",
    "            print(result.stdout)\n",
    "            print(result.stderr)\n",
    "        else:\n",
    "            print(\"done\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@output.capture()\n",
    "def download(_):\n",
    "    from IPython.display import HTML\n",
    "\n",
    "    for pdf in pdf_uploader.value:\n",
    "        pdf_name = pdf.name.replace(\" \", \"_\")\n",
    "        js_code = f\"\"\"\n",
    "            var a = document.createElement('a');\n",
    "            var href = window.location.href;\n",
    "            n = href.includes('gesis') ? 7 : 5;\n",
    "            var url = href.split('/').slice(0, n).join(\"/\"); \n",
    "            a.setAttribute('download','');\n",
    "            a.setAttribute('href', url + '/files/bin/pdf/{pdf_name}');\n",
    "            a.click()\n",
    "        \"\"\"\n",
    "        with output:\n",
    "            display(HTML(f\"<script>{js_code}</script>\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "process_button = widgets.Button(description=\"Process\", icon=\"check\", button_style=\"success\")\n",
    "download_button = widgets.Button(description=\"Download\", icon=\"download\", button_style=\"warning\")\n",
    "clear_button = widgets.Button(description=\"Clear\", icon=\"trash\", button_style=\"danger\")\n",
    "clear_button.on_click(clear)\n",
    "download_button.on_click(download)\n",
    "process_button.on_click(process)\n",
    "\n",
    "top = widgets.VBox(\n",
    "    [\n",
    "        widgets.HTML(value=\"Tag position/width in fraction of the page\"),\n",
    "        widgets.HBox([widgets.HTML(value=\"Select pdf(s) to tag\"), pdf_uploader, xpos]),\n",
    "        widgets.HBox([widgets.HTML(value=\"Select tag image\"), tag_uploader, ypos]),\n",
    "        width,\n",
    "    ],\n",
    "    layout=widgets.Layout(display=\"flex\", align_items=\"flex-end\"),\n",
    ")\n",
    "\n",
    "bottom = widgets.HBox([process_button, download_button, clear_button])\n",
    "\n",
    "widgets.HBox(\n",
    "    [\n",
    "        widgets.HTML(value=\"<h1>Tag Application</h1>\"),\n",
    "        top,\n",
    "        widgets.HTML(value=\"<p style='margin-bottom:1cm;'></p>\"),\n",
    "        bottom,\n",
    "        widgets.VBox([widgets.HTML(value=\"<h2>Logs</h2>\"), output]),\n",
    "    ],\n",
    "    layout=widgets.Layout(display=\"flex\", flex_flow=\"column\", align_items=\"center\", width=\"100%\"),\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}