from collective.ftw.upgrade import UpgradeStep
from logging import getLogger
from plone import api
from ploneintranet.suite.setuphandlers import create_office_templates_files
from ploneintranet.suite.setuphandlers import create_office_templates_folder
from ploneintranet.workspace.config import TEMPLATES_FOLDER

log = getLogger(__name__)


class ProvideDefaultOfficeTemplates(UpgradeStep):
    """Provide default office templates."""

    def __call__(self):
        create_office_templates_folder(self.portal_setup)
        moved = self.move_existing_templates()
        if not moved:
            create_office_templates_files(self.portal_setup)

    def move_existing_templates(self):
        templates_folder = api.portal.get().get(TEMPLATES_FOLDER)
        office_templates_folder = templates_folder.get("office")
        count = 0
        for id, obj in templates_folder.objectItems():
            if obj.portal_type != "File":
                continue
            if id in office_templates_folder.objectIds():
                continue
            api.content.move(source=obj, target=office_templates_folder, id=id)
            count += 1
        if count:
            log.info("Moved %s existing office templates into templates/office", count)
        return count
