from ldt.ldt_utils.models import Project

from django.contrib.auth import get_user_model
import lxml.etree

import logging

# pylint: disable=C0103
logger = logging.getLogger(__name__)

# pylint: disable=C0103
User = get_user_model()

"""
Merge several projects in one for a given content. All ensembles are copied into one project
"""
# pylint: disable=R0903
class ProjectMerger(object):

    def __init__(self, content, projects):
        self.content = content
        self.projects = projects

    # pylint: disable=R0914
    def get_merged_project(self, shot_by_shot=True, only_visible=True):

        # New project
        contents = [self.content,]
        # Get user
        user = User.objects.get(username="admin")

        proj = Project.create_project(title="Merged project",
                                      user=user, contents=contents,
                                      description=u"", set_icon=False)

        doc = lxml.etree.fromstring(proj.ldt_encoded)
        annot_node = doc.xpath("/iri/annotations")[0]
        content_node = lxml.etree.SubElement(annot_node, 'content')
        content_node.set('id', self.content.iri_id)
        display_node = doc.xpath('/iri/displays/display')[0]
        ctt_disp_node = display_node.xpath('content[@id="' + self.content.iri_id + '"]')[0]
        # remove shot by shot from display
        if not shot_by_shot:
            dec_node = ctt_disp_node.xpath('decoupage[@id="de_PPP"]')
            if len(dec_node) > 0:
                dec_node = dec_node[0]
                if dec_node is not None:
                    ctt_disp_node.remove(dec_node)

        # Parse all projects
        for p in self.projects:
            p_xml = lxml.etree.fromstring(p.ldt_encoded)
            # We only keep the decoupages (cuttings) visible in the default
            # view, which means the first display.
            first_display = p_xml.xpath('/iri/displays/display')[0]
            disp_node_list = first_display.xpath('content[@id="' + self.content.iri_id + '"]')
            if len(disp_node_list) == 0:
                # project seems broken passing
                logger.info(
                    "Get merged project : this project display %s does not contains the content %s",
                    p.ldt_id,
                    self.content.iri_id)
                continue
            current_disp_node = disp_node_list[0]
            # First version of ensemble
            ens = p_xml.xpath(
                '/iri/annotations/content[@id="' +
                self.content.iri_id +
                '"]/ensemble')
            for e in ens:
                content_node.append(e)
                # Update display
                for c in e.xpath('decoupage'):
                    if not only_visible or \
                        (only_visible and \
                         len(current_disp_node.xpath('decoupage[@id="' + c.get('id') + '"]')) > 0):
                        c_node = lxml.etree.SubElement(ctt_disp_node, 'decoupage')
                        c_node.set(u'idens', e.get('id'))
                        c_node.set(u'id', c.get('id'))
            # Second version of ensemble
            ens = p_xml.xpath('/iri/annotations/content[@id="' +
                              self.content.iri_id +
                              '"]/ensembles/ensemble')
            for e in ens:
                content_node.append(e)
                # Update display
                for c in e.xpath('decoupage'):
                    if not only_visible or \
                        (only_visible and \
                         len(current_disp_node.xpath('decoupage[@id="' +
                                                     c.get('id') +
                                                     '"]')) > 0):
                        c_node = lxml.etree.SubElement(ctt_disp_node, 'decoupage')
                        c_node.set(u'idens', e.get('id'))
                        c_node.set(u'id', c.get('id'))

        proj.ldt = lxml.etree.tostring(doc, pretty_print=True)

        return proj
