import imghdr
import urllib
import zipfile

from bs4 import BeautifulSoup

from modules.logs.log_config import get_logger
from patch.include import *
from tqdm import tqdm


def build_content(attachments):
    clipSvg = f'<svg style="width:20px;height:20px;margin-bottom:-5px;" viewBox="0 0 24 24"><path fill="#AAA" ng-attr-d="{{icon.data}}" d="M16.5,6V17.5A4,4 0 0,1 12.5,21.5A4,4 0 0,1 8.5,17.5V5A2.5,2.5 0 0,1 11,2.5A2.5,2.5 0 0,1 13.5,5V15.5A1,1 0 0,1 12.5,16.5A1,1 0 0,1 11.5,15.5V6H10V15.5A2.5,2.5 0 0,0 12.5,18A2.5,2.5 0 0,0 15,15.5V5A4,4 0 0,0 11,1A4,4 0 0,0 7,5V17.5A5.5,5.5 0 0,0 12.5,23A5.5,5.5 0 0,0 18,17.5V6H16.5Z"></path></svg>'
    content = """<table class="attachments">
              <tbody><tr class="header-row">
                <th class="filename-column">
                    Файл
                </th>
                <th class="modified-column">
                    Изменено
                </th>
                <th class="actions-column">
                  Действия
                </th>
            </tr>
        </tbody>
        <tbody>"""
    for attachment in attachments:
        attachment.load_fields(['cmf_modified_at', 'cmf_modified_by.name'])
        deleteSvg = f'<svg class="icon delete-icon" data-action-type="delete" data-attachment-id="{attachment.id.value}" viewBox="0 0 24 24"><path style="pointer-events: none;" fill="#AAA" d="M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19M8,9H16V19H8V9M15.5,4L14.5,3H9.5L8.5,4H5V6H19V4H15.5Z"><title>Удалить</title></path></svg>'
        downloadSvg = f'<svg class="icon download-icon" data-action-type="download" data-href="{attachment.url.value}" data-filename="{attachment.name.value}" data-attachment-id="{attachment.id.value}" viewBox="0 0 24 24"><path style="pointer-events: none;" fill="#AAA" d="M13,5V11H14.17L12,13.17L9.83,11H11V5H13M15,3H9V9H5L12,16L19,9H15V3M19,18H5V20H19V18Z"></path></svg>'
        content += f"""<tr class="attachment-row" id="{attachment.id.value}" data-attachment-id="{attachment.id.value}">
        <td class="filename-column">
            {clipSvg}&nbsp;{attachment.name.value}
        </td>
        <td class="modified-column">
          <span class="modified-at">{attachment.cmf_modified_at}</span>
          <span class="modified-by">{attachment.cmf_modified_by.value.name.value}</span>
        </td>
        <td class="actions-column">{downloadSvg}{deleteSvg}</td>
      </tr>"""
    content += '</tbody></table>'
    return content


def buildHtml(content, doc_id):
    cloudSvg = f"""<svg style="width:30px;height:30px;margin-bottom:-5px;" viewBox="0 0 24 24"><path fill="#AAA" d="m18.746 20.334a1 1 0 0 1 -.081 1.413l-1.586 1.414a2.9 2.9 0 0 1 -2.064.839 3.013 3.013 0 0 1 -2.136-.882l-1.544-1.374a1 1 0 0 1 1.33-1.494l1.335 1.194v-7.444a1 1 0 0 1 2 0v7.445l1.335-1.192a1 1 0 0 1 1.411.081zm-.39-12.973a1.088 1.088 0 0 1 -.722-.735 8 8 0 0 0 -15.489.842 7.657 7.657 0 0 0 .8 5.18 5.448 5.448 0 0 0 -2.888 5.652 5.843 5.843 0 0 0 5.626 4.7h2.317a1 1 0 0 0 0-2h-2.317a3.81 3.81 0 0 1 -3.646-2.982 3.469 3.469 0 0 1 1.834-3.6 1.993 1.993 0 0 0 .793-2.685 6 6 0 1 1 11.06-4.513 3.1 3.1 0 0 0 2.045 2.052 5.971 5.971 0 0 1 4.212 6.21 5.377 5.377 0 0 1 -1.111 2.909 1 1 0 0 0 1.586 1.219 7.466 7.466 0 0 0 1.52-3.972 7.96 7.96 0 0 0 -5.62-8.277z"/></svg>"""
    downoladAllContainer = f"""
    <div class="plugin-attachments-download-all-container">
        <button data-action-type="download-all" data-document-id="{doc_id}">
          <svg class="icon" viewBox="0 0 24 24">
            <path
              style="pointer-events: none;"
              fill="#AAA"
              d="M13,5V11H14.17L12,13.17L9.83,11H11V5H13M15,3H9V9H5L12,16L19,9H15V3M19,18H5V20H19V18Z"
            ></path>
          </svg>
          <span style="pointer-events: none;">Скачать Все</span>
        </button>
      </div>
    """
    return f"""<div class="plugin_attachments_table_container" data-attachments-table="true" contenteditable="false">
      {content}
      <div class="plugin-attachments-upload-container">
        <div class="attachments-table-drop-zone dropzone"></div>
        <div class="attachments-table-text">{cloudSvg}&nbsp;Перенесите или
          <label for="input-file">
            <span id="file-upload" class="pseudo-link" aria-hidden="true">загрузите файлы</span>
            <input id="input-file" class="input-file" accept=".jpg, .jpeg, .png, .txt, .pdf" type="file" />
          </label>
        </div>
      </div>
      {downoladAllContainer}
    </div>"""


@app_context(commit=True)
def patch():
    """
    Проходимся по документам с вложениями и добавляем списко вложений в текст документа если нету
    """
    logger = get_logger('kn_client_add_attach_content')
    start = 0
    step = 1000
    total = models.CmfDocument.count(filter=['cmf_import_id', '!=', None])
    logger.info(f'total={total}')
    res = []
    with cmfutil.disable_notify():
        while True:
            docs = models.CmfDocument.list(filter=['cmf_import_id', '!=', None], fields=['attachments.url', 'text',
                                                                                         'text_draft',
                                                                                         'attachments.cmf_modified_at'],
                                           slice=[start, start + step])
            for doc in tqdm(docs):
                logger.info(f'Обрабатываем {doc.code}')
                if not doc.attachments or 'plugin-attachments-upload-container' in doc.text.value:
                    continue
                images = 0
                for attch in doc.attachments:
                    try:
                        if attch.file_exists:
                            if imghdr.what(attch.full_path_file):
                                images += 1
                    except OSError as e:
                        logger.error(str(e))
                        attch.name = 'bad'
                        attch.save(only_data=True)
                        attch.delete()
                        images += 1

                if len(doc.attachments) == images:
                    continue
                doc_soup = BeautifulSoup(doc.text.value, 'html.parser')
                tags = doc_soup.find_all(lambda tag2: tag2.has_attr('href') and not tag2.has_attr('cmf_converted'))
                logger.info(f'tags={len(tags)}')
                logger.info(f'attachments={len(doc.attachments.value)}')
                for tag in tags:
                    # logger.info(tag.attrs['href'])
                    for attach in doc.attachments.value:
                        if attach.name.value in urllib.parse.unquote(tag.attrs['href']):
                            logger.info(f"Заменили ссылку {tag.attrs['href']} в {doc.code}")
                            tag.attrs['href_orig'] = tag.attrs['href']
                            tag.attrs['href'] = attach.url.value
                            tag.attrs['cmf_converted'] = True
                logger.info(f'Прикрепляем вложения')
                htmltag = buildHtml(build_content(doc.attachments), doc.id.value)
                doc.text_draft = f'{doc_soup} {htmltag}'
                logger.info(f'Сохраняем')
                doc.save()
                logger.info(f'Утверждаем')
                doc.do_approve()
                res.append(doc.code.value)
                models.CmfDocument.dp.commit()
            if not docs:
                break
            start += step
    logger.info(str(res))


if __name__ == "__main__":
    patch()
