from collections import OrderedDict
from collective.mustread.db import getSession
from collective.mustread.interfaces import IMustReadSettings
from collective.mustread.models import Base
from importlib.resources import files
from plone import api
from plone.app.textfield.value import RichTextValue
from plone.i18n.normalizer.interfaces import IURLNormalizer
from plone.namedfile.file import NamedBlobImage
from ploneintranet.news.behaviors import INewsMeta
from ploneintranet.news.content import INewsApp
from zope.component import getUtility

import logging
import os

log = logging.getLogger(__name__)


def setupVarious(context):
    initialize_mustread_db()
    create_news_app()


def initialize_mustread_db(*args):
    if api.env.test_mode() or "robot-server" in os.environ.get("_", ""):
        # tests provide own tempDb
        return
    try:
        record = api.portal.get_registry_record(
            "connectionstring", interface=IMustReadSettings
        )
    except api.exc.InvalidParameterError:
        record = ""
    if not record or "memory" in record:
        dbpath = "%s/var/mustread.db" % os.getcwd()
        record = "sqlite:///%s" % dbpath
        log.warning("SQL storage not properly configured. Forcing: %s", record)
        api.portal.set_registry_record(
            "connectionstring", record, interface=IMustReadSettings
        )
    log.info("Initializing SQL db: %s" % record)
    session = getSession()
    Base.metadata.create_all(session.bind.engine, checkfirst=True)


def create_news_app():
    portal = api.portal.get()
    if "news" in portal:
        app_obj = portal.news
        if not INewsApp.providedBy(app_obj):
            api.content.delete(obj=app_obj, check_linkintegrity=False)
    if "news" not in portal:
        api.content.create(
            container=portal,
            type="ploneintranet.news.app",
            title="News publisher",
            id="news",
            safe_id=False,
            condition="object/@@publisher/get_target_sections|nothing",
        )
    app_obj = portal.news
    # if the app is not published we will publish it
    if api.content.get_state(app_obj) != "published":
        try:
            api.content.transition(app_obj, to_state="published")
        except BaseException:
            log.exception("Cannot publish the app: %r", app_obj)
    # there always must be 1 or more news sections
    if not app_obj.objectValues():
        section = api.content.create(
            container=app_obj,
            type="ploneintranet.news.section",
            title="Company News",
            id="company-news",
            safe_id=False,
            navigation="main",
        )
        if not app_obj.columns:
            app_obj.columns = {
                "1": OrderedDict(),
                "2": OrderedDict(),
                "3": OrderedDict(),
            }
        app_obj.columns["2"][section.UID()] = {
            "num_items": 4,
            "show_title": False,
            "show_border": False,
            "grid": "1-3",
            "show_descriptions": True,
            "num_rows": "2",
        }
    return app_obj


def setupTestdata(context):
    news = api.portal.get()["news"]
    company_news = news["company-news"]
    press_mentions = api.content.create(
        container=news,
        type="ploneintranet.news.section",
        title="Press Mentions",
        id="press-mentions",
        safe_id=False,
    )
    for i in range(5):
        create_news_items(company_news, i)
    for i in range(5, 10):
        create_news_items(press_mentions, i)


def create_news_items(section, i):
    seq = i + 1
    title = LOREMIPSUM_TITLES[i]
    objid = getUtility(IURLNormalizer).normalize(title)
    item = api.content.create(
        container=section, type="News Item", id=objid, title=title
    )
    INewsMeta(item).magazine_home = True
    item.description = LOREMIPSUM_DESCRIPTIONS[i]
    item.text = RichTextValue(
        raw=LOREMIPSUM_PARAGRAPH,
        mimeType="text/plain",
        outputMimeType="text/x-html-safe",
    )
    img_name = f"{seq:02d}.jpg"
    img_data = (
        files("ploneintranet.news") / f"profiles/test/images/{img_name}"
    ).read_bytes()

    item.image = NamedBlobImage(data=img_data, filename=img_name)
    if i % 2:
        item.must_read = True

    item.setEffectiveDate(f"2016/09/{seq:02d}")
    api.content.transition(item, "publish")


LOREMIPSUM_TITLES = [
    "Etiam augue.",
    "Fames vitae.",
    "Dolor etiam mauris lobortis nibh torquent dis natoque torquent cubilia.",
    "Class lacus semper erat laoreet et accumsan gravida aliquet mauris luctus mi eros.",  # noqa: E501
    "Vitae ipsum metus nonummy tempus lorem netus vivamus dui ad cursus leo orci inceptos eni fames.",  # noqa: E501
    "Proin netus.",
    "Felis proin senectus quis non est.",
    "Massa lacus sociis molestie odio pretium.",
    "Class velit dis velit integer.",
    "Fusce fames.",
]

LOREMIPSUM_DESCRIPTIONS = [
    "Magna vitae lorem elementum vel pellentesque. Metus proin purus.",
    "Porta proin morbi pulvinar ac pede vivamus mus mi eros congue egestas. Justo vitae quam placerat massa facilisis.",  # noqa: E501
    "Dolor lorem. Fusce risus.",
    "Metus risus. Velit netus nostra parturient consectetuer quisque sem pede.",
    "Morbi risus sodales hac dignissim fusce at fusce at quis nisl vel cras venenatis. Netus etiam eros sem quis volutpat.",  # noqa: E501
    "Massa nulla class primis tellus. Fames metus facilisi urna tellus.",
    "Fames neque tempor eu ornare. Vitae metus cubilia auctor ve felis.",
    "Porta proin est netus vel parturient. Velit netus metus ullamcorper facilisi eros.",  # noqa: E501
    "Felis dolor mattis eros venenatis class fames a eget ipsum. Vitae felis tempus orci euismod ad interdum conubia morbi vestibulum bibendum.",  # noqa: E501
    "Metus risus per nisl habitant scelerisque est duis. Justo etiam primis natoque.",
]

LOREMIPSUM_PARAGRAPH = """
Lorem ipsum dolor sit amet, pro te nullam pericula, ius id legere nusquam. Nec expetenda efficiendi ad, mei mollis equidem assentior in. Dicta mediocritatem eum cu. Et verear suavitate patrioque has, dicant labitur pro id.

Usu voluptatum suscipiantur ne. Ei tota natum splendide vel, ex aliquid urbanitas sed. Mei meliore postulant ei. Ad mea elit probo, sea ne velit facilisi. Ad liber volumus eum, sed cu mazim albucius.

Per cu choro urbanitas, pri ei oratio postea, ridens facilisis ad usu. Ludus aliquam persequeris est eu, ea option denique referrentur mei. Probatus gloriatur ius no, nam affert melius facilis in. Amet nemore appetere nec ne. Referrentur liberavisse qui at, cu facer animal praesent quo. Dictas dolorem adversarium ne eam. Ne voluptaria adipiscing persequeris mea, esse molestie democritum et usu.

Illud justo nostro quo at, at his dico ridens postulant. Mel magna deserunt gubergren ea, eam te cetero deseruisse signiferumque. Duo lorem signiferumque ut, no labores accusamus eam. Usu ne errem ridens possim, ei eos laudem quodsi pericula. Eu tractatos tincidunt est, te his natum posidonium quaerendum.

Pro everti quaeque conclusionemque id, latine erroribus usu at. An postea voluptaria philosophia sea, nec modo dico disputando ne, eam an ridens viderer antiopam. At his consulatu repudiandae. Tale malis possim cu has, eu soluta lucilius est, vel bonorum explicari ut. Eu mea quot vivendo temporibus. Has posse malis neglegentur ea, eu pro hinc falli. Pri case ullum id, tale falli error at nam.
"""  # noqa: E501
