<commit_before># Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

"""Handlers document entries."""

from flask import current_app

from ggrc import models
from ggrc.converters import errors
from ggrc.converters.handlers import handlers
from ggrc.login import get_current_user_id


class RequestLinkHandler(handlers.ColumnHandler):
  """Base class for request documents handlers."""

  @staticmethod
  def _parse_line(line):
    """Parse a single line and return link and title.

    Args:
      line: string containing a single line from a cell.

    Returns:
      tuple containing a link and a title.
    """
    line = line.strip()
    return line, line

  def parse_item(self, has_title=False):
    """Parse document link lines.

    Returns:
      list of documents for all URLs and evidences.
    """
    documents = []
    user_id = get_current_user_id()
    for line in self.raw_value.splitlines():
      link, title = self._parse_line(line)
      if not (link and title):
        return []
      documents.append(models.Document(
          link=link,
          title=title,
          modified_by_id=user_id,
          context=self.row_converter.obj.context,
      ))

    return documents

  @staticmethod
  def _get_link_str(documents):
    """Generate a new line separated string for all document links.

    Returns:
      string containing all URLs and titles.
    """
    return "\n".join(
        "{} {}".format(document.link, document.title)
        for document in documents
    )

  def set_obj_attr(self):
    self.value = self.parse_item()


class RequestEvidenceHandler(RequestLinkHandler):
  """Handler for evidence field on request imports."""

  @staticmethod
  def _parse_line(line):
    """Parse a single line and return link and title.

    Args:
      line: string containing a single line from a cell.

    Returns:
      tuple containing a link and a title.
    """
    parts = line.strip().split()
    if len(parts) == 1:
      return parts[0], parts[0]

    return parts[0], " ".join(parts[1:])

  def get_value(self):
    return self._get_link_str(self.row_converter.obj.documents)

  def insert_object(self):
    """Update request evidence values

    This function adds missing evidence and remove existing ones from requests.
    The existing evidence with new titles just change the title.
    """
    if not self.value or self.row_converter.ignore:
      return

    new_link_map = {doc.link: doc for doc in self.value}
    old_link_map = {doc.link: doc for doc in self.row_converter.obj.documents}
    for new_link, new_doc in new_link_map.iteritems():
      if new_link in old_link_map:
        old_link_map[new_link].title = new_doc.title
      else:
        self.row_converter.obj.documents.append(new_doc)

    for old_link, old_doc in old_link_map.iteritems():
      if old_link not in new_link_map:
        self.row_converter.obj.documents.remove(old_doc)

  def set_value(self):
    """This should be ignored with second class attributes."""


class RequestUrlHandler(RequestLinkHandler):
  """Handler for URL field on request imports."""

  @staticmethod
  def _parse_line(line):
    """Parse a single line and return link and title.

    Args:<commit_msg>Change _parse_line function type<commit_after># Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

"""Handlers document entries."""

from flask import current_app

from ggrc import models
from ggrc.converters import errors
from ggrc.converters.handlers import handlers
from ggrc.login import get_current_user_id


class RequestLinkHandler(handlers.ColumnHandler):
  """Base class for request documents handlers."""

  def _parse_line(self, line):
    """Parse a single line and return link and title.

    Args:
      line: string containing a single line from a cell.

    Returns:
      tuple containing a link and a title.
    """
    # pylint: disable=no-self-use
    line = line.strip()
    return line, line

  def parse_item(self, has_title=False):
    """Parse document link lines.

    Returns:
      list of documents for all URLs and evidences.
    """
    documents = []
    user_id = get_current_user_id()
    for line in self.raw_value.splitlines():
      link, title = self._parse_line(line)
      if not (link and title):
        return []
      documents.append(models.Document(
          link=link,
          title=title,
          modified_by_id=user_id,
          context=self.row_converter.obj.context,
      ))

    return documents

  @staticmethod
  def _get_link_str(documents):
    """Generate a new line separated string for all document links.

    Returns:
      string containing all URLs and titles.
    """
    return "\n".join(
        "{} {}".format(document.link, document.title)
        for document in documents
    )

  def set_obj_attr(self):
    self.value = self.parse_item()


class RequestEvidenceHandler(RequestLinkHandler):
  """Handler for evidence field on request imports."""

  def _parse_line(self, line):
    """Parse a single line and return link and title.

    Args:
      line: string containing a single line from a cell.

    Returns:
      tuple containing a link and a title.
    """
    # pylint: disable=no-self-use
    parts = line.strip().split()
    if len(parts) == 1:
      return parts[0], parts[0]

    return parts[0], " ".join(parts[1:])

  def get_value(self):
    return self._get_link_str(self.row_converter.obj.documents)

  def insert_object(self):
    """Update request evidence values

    This function adds missing evidence and remove existing ones from requests.
    The existing evidence with new titles just change the title.
    """
    if not self.value or self.row_converter.ignore:
      return

    new_link_map = {doc.link: doc for doc in self.value}
    old_link_map = {doc.link: doc for doc in self.row_converter.obj.documents}
    for new_link, new_doc in new_link_map.iteritems():
      if new_link in old_link_map:
        old_link_map[new_link].title = new_doc.title
      else:
        self.row_converter.obj.documents.append(new_doc)

    for old_link, old_doc in old_link_map.iteritems():
      if old_link not in new_link_map:
        self.row_converter.obj.documents.remove(old_doc)

  def set_value(self):
    """This should be ignored with second class attributes."""


class RequestUrlHandler(RequestLinkHandler):
  """Handler for URL field on request imports."""

  def _parse_line(self, line):
    """Parse a single line and return link and title.

    Args:
{'fraction_non_alphanumeric': 0.09382116289661455, 'fraction_numerical': 0.003339911947775922, 'mean_word_length': 3.0817843866171004, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1676831', 'n_tokens_mistral': 1998, 'n_tokens_neox': 1913, 'n_words': 618}