# -*- coding: utf-8 -*-
"""Parser for {{ plugin_name|lower|replace('_',' ')}} database.

SQLite database path: {{ test_file_path }}
SQLite database Name: {{ database_name }}
"""

from __future__ import unicode_literals

from dfdatetime import posix_time as dfdatetime_posix_time

from plaso.containers import time_events
from plaso.lib import eventdata
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import interface
{% for query_name, query in queries.items()|sort(false) %}
class {{ class_name }}{{ query_name }}EventData(events.EventData):
  """{{ plugin_name|replace('_',' ')}} {{query_name|lower}} event data.

  Attributes:
    {% for attr in query_columns[query_name] %}{{attr}}: <ADD DESCRIPTION HERE>
    {% endfor %}
  """

  DATA_TYPE = '{{ data_types[query_name] }}'

  def __init__(self):
    """Initializes event data."""
    super({{ class_name }}{{ query_name|capitalize }}EventData, self).__init__(data_type=self.DATA_TYPE)
    {% for attr in query_columns[query_name]|sort(false) %}self.{{ attr }} = None
    {% endfor %}{% endfor %}

class {{ class_name }}Plugin(interface.SQLitePlugin):
  """Parser for {{ class_name }}"""

  NAME = '{{ plugin_name }}'
  DESCRIPTION = 'Parser for {{ class_name }}'

  QUERIES = [
  {% for query_name, query in queries.items()|sort(false) %}
      ((
          '{{ query|wordwrap(width=69,break_long_words=False,wrapstring="'\n          '") }}'),
       'Parse{{ query_name }}Row'){% if not loop.last %},{% endif %}{% endfor %}]

  REQUIRED_TABLES = frozenset([
      {% for table in required_tables %}'{{ table }}'{% if not loop.last %},
      {% endif %}{% endfor %}])

  SCHEMAS = [{  {% for table, schema in database_schema.items()|sort(false) %}
      '{{table}}': (
          '{{schema|wordwrap(width=64,wrapstring="'\n          '")}}'){% if not loop.last %},{% endif %}{% endfor%}}]

{% for query_name, query in queries.items()|sort(false) %}
  def Parse{{ query_name }}Row(self, parser_mediator, query, row, **unused_kwargs):
    """Parses a row from the database.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      query (str): query that created the row.
      row (sqlite3.Row): row resulting from query.
    """
    # Note that pysqlite does not accept a Unicode string in row['string'] and
    # will raise "IndexError: Index must be int or string".

    event_data = {{ class_name }}{{ query_name|capitalize }}EventData()
    {% for column in query_columns[query_name]|sort(false) %}event_data.{{ column }} = row['{{ column}}']
    {% endfor %}
    {% for column in timestamp_columns[query_name]|sort(false) %}
    timestamp_string = row['{{ column }}']
    if timestamp_string:
      # Convert the floating point value to an integer.
      try:
        timestamp = int(timestamp_string, 10)

        # TODO: Convert to a correct timestamp conversion if needed, defaults to
        # POSIX.
        date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
        # TODO: Add correct time field for None value.  Example: eventdata.EventTimestamp.UPDATE_TIME
        event = time_events.DateTimeValuesEvent(date_time, None)
        parser_mediator.ProduceEventWithEventData(event, event_data)
      except (TypeError, ValueError):
        parser_mediator.ProduceExtractionError(
            'invalid timestamp value: {0!s}'.format(timestamp_string))
    {% endfor %}

{% endfor %}

sqlite.SQLiteParser.RegisterPlugin({{ class_name }}Plugin)
