# Path: siptools/scripts/import_object.py
# def import_object(**kwargs):
#     """Import files to generate digital objects.
# 
#     If attributes charset, file_format, identifier, checksum or
#     date_created are not given, then these are created automatically.
# 
#     :attributes: Given arguments
#                  filepaths: Files or a directory to import
#                  workspace: Workspace path
#                  base_path: Base path of digital objects
#                  skip_wellformed_check: True skips well-formedness
#                                         checking
#                  charset: Character encoding of a file
#                  file_format: File format and version (tuple) of a file
#                  format_registry: Format registry name and value (tuple)
#                  identifier: File identifier type and value (tuple)
#                  checksum: Checksum algorithm and value (tuple)
#                  date_created: Creation date of a file
#                  order: Order number of a file
#                  event_datetime: Timestamp of the event
#                  event_target: The target of the event
#                  stdout: True prints output to stdout
#                  supplementary: Object type for supplementary files
#     """
#     attributes = _attribute_values(kwargs)
#     # Loop files and create premis objects
#     files = collect_filepaths(dirs=attributes["filepaths"],
#                               base=attributes["base_path"])
#     creator = PremisCreator(attributes["workspace"])
#     agents = []
#     for filepath in files:
# 
#         # If the given path is an absolute path and base_path is current
#         # path (i.e. not given), relpath will return ../../.. sequences,
#         # if current path is not part of the absolute path. In such case
#         # we will use the absolute path for filerel and omit base_path
#         # relation.
#         if attributes["base_path"] not in ['.']:
#             filerel = os.path.relpath(filepath, attributes["base_path"])
#         else:
#             filerel = filepath
# 
#         properties = {}
#         if attributes["order"] is not None:
#             properties['order'] = six.text_type(attributes["order"])
#         properties["supplementary"] = attributes["supplementary"]
# 
#         (streams, scraper_info) = creator.add_premis_md(
#             filepath, attributes, filerel=filerel, properties=properties)
#         for index in scraper_info:
#             agents.append(_parse_scraper_tools(scraper_info[index]))
# 
#         grade = streams[0]['properties']['grade']
# 
#     is_native = grade in (
#         file_scraper.defaults.BIT_LEVEL,
#         file_scraper.defaults.BIT_LEVEL_WITH_RECOMMENDED
#     )
# 
#     is_validated = (
#         not bool(attributes["skip_wellformed_check"])
#         and not is_native
#     )
# 
#     creator.write(stdout=attributes["stdout"])
# 
#     # Create events documenting the technical metadata creation
#     _create_events(
#         workspace=attributes["workspace"],
#         base_path=attributes["base_path"],
#         filepaths=attributes["filepaths"],
#         event_datetime=attributes["event_datetime"],
#         event_target=attributes["event_target"],
#         identification_event=not bool(attributes["file_format"]),
#         validation_event=is_validated,
#         checksum_event=not bool(attributes["checksum"]),
#         agents=agents
#     )
# 
# Path: siptools/utils.py
# def fsdecode_path(filename):
#     """
#     Decode byte filenames using the file system encoding.
# 
#     :filename: File path to decode
#     :returns: Decoded path
#     :raises: TypeError if wrong type given
#     """
#     if isinstance(filename, six.binary_type):
#         return filename.decode(encoding=sys.getfilesystemencoding())
#     if isinstance(filename, six.text_type):
#         return filename
# 
#     raise TypeError("Value is not a (byte) string")
# 
# def load_scraper_json(json_name):
#     """
#     Load scraper stream from JSON file.
# 
#     :json_name: JSON file name
#     :returns: Stream metadata from JSON file.
#     """
#     with open(json_name, 'rt') as json_file:
#         streams = json.load(json_file)
#     new_streams = {}
#     for index in streams:
#         new_streams[int(index)] = streams[index]
#         new_streams[int(index)]["index"] = \
#             int(new_streams[int(index)]["index"])
#     return new_streams
# 
# def read_md_references(workspace, ref_file):
#     """Read all the MD IDs as a dictionary.
# 
#     :workspace: path to workspace directory
#     :ref_file: Metadata reference file
#     :returns: A dict of references or None if reference file doesn't
#               exist
#     """
#     reference_file = os.path.join(workspace, ref_file)
# 
#     if os.path.isfile(reference_file):
#         references = {}
#         with open(reference_file) as in_file:
#             for line in in_file:
#                 references.update(json.loads(line))
#         return references
#     return None
# 
# Path: siptools/xml/mets.py
# NAMESPACES = {
#     'mets': 'http://www.loc.gov/METS/',
#     'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
#     'premis': 'info:lc/xmlns/premis-v2',
#     'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
#     'xlink': 'http://www.w3.org/1999/xlink',
#     'mix': 'http://www.loc.gov/mix/v20',
#     'ead3': 'http://ead3.archivists.org/schema/',
#     'addml': 'http://www.arkivverket.no/standarder/addml',
#     'audiomd': 'http://www.loc.gov/audioMD/',
#     'videomd': 'http://www.loc.gov/videoMD/'
# }


import datetime
import io
import os.path
import pytest
import six
import lxml.etree as ET
from siptools.scripts import import_object
from siptools.utils import fsdecode_path, load_scraper_json, read_md_references
from siptools.xml.mets import NAMESPACES
# encoding: utf-8
"""Unit tests for ``siptools.scripts.import_object`` module."""
from __future__ import unicode_literals






def get_amd_file(path,
                 input_file,
                 stream=None,
                 ref_file='import-object-md-references.jsonl',
                 suffix='-PREMIS%3AOBJECT-amd.xml'):
    """Get id."""

# Path: siptools/scripts/import_object.py
# def import_object(**kwargs):
#     """Import files to generate digital objects.
# 
#     If attributes charset, file_format, identifier, checksum or
#     date_created are not given, then these are created automatically.
# 
#     :attributes: Given arguments
#                  filepaths: Files or a directory to import
#                  workspace: Workspace path
#                  base_path: Base path of digital objects
#                  skip_wellformed_check: True skips well-formedness
#                                         checking
#                  charset: Character encoding of a file
#                  file_format: File format and version (tuple) of a file
#                  format_registry: Format registry name and value (tuple)
#                  identifier: File identifier type and value (tuple)
#                  checksum: Checksum algorithm and value (tuple)
#                  date_created: Creation date of a file
#                  order: Order number of a file
#                  event_datetime: Timestamp of the event
#                  event_target: The target of the event
#                  stdout: True prints output to stdout
#                  supplementary: Object type for supplementary files
#     """
#     attributes = _attribute_values(kwargs)
#     # Loop files and create premis objects
#     files = collect_filepaths(dirs=attributes["filepaths"],
#                               base=attributes["base_path"])
#     creator = PremisCreator(attributes["workspace"])
#     agents = []
#     for filepath in files:
# 
#         # If the given path is an absolute path and base_path is current
#         # path (i.e. not given), relpath will return ../../.. sequences,
#         # if current path is not part of the absolute path. In such case
#         # we will use the absolute path for filerel and omit base_path
#         # relation.
#         if attributes["base_path"] not in ['.']:
#             filerel = os.path.relpath(filepath, attributes["base_path"])
#         else:
#             filerel = filepath
# 
#         properties = {}
#         if attributes["order"] is not None:
#             properties['order'] = six.text_type(attributes["order"])
#         properties["supplementary"] = attributes["supplementary"]
# 
#         (streams, scraper_info) = creator.add_premis_md(
#             filepath, attributes, filerel=filerel, properties=properties)
#         for index in scraper_info:
#             agents.append(_parse_scraper_tools(scraper_info[index]))
# 
#         grade = streams[0]['properties']['grade']
# 
#     is_native = grade in (
#         file_scraper.defaults.BIT_LEVEL,
#         file_scraper.defaults.BIT_LEVEL_WITH_RECOMMENDED
#     )
# 
#     is_validated = (
#         not bool(attributes["skip_wellformed_check"])
#         and not is_native
#     )
# 
#     creator.write(stdout=attributes["stdout"])
# 
#     # Create events documenting the technical metadata creation
#     _create_events(
#         workspace=attributes["workspace"],
#         base_path=attributes["base_path"],
#         filepaths=attributes["filepaths"],
#         event_datetime=attributes["event_datetime"],
#         event_target=attributes["event_target"],
#         identification_event=not bool(attributes["file_format"]),
#         validation_event=is_validated,
#         checksum_event=not bool(attributes["checksum"]),
#         agents=agents
#     )
# 
# Path: siptools/utils.py
# def fsdecode_path(filename):
#     """
#     Decode byte filenames using the file system encoding.
# 
#     :filename: File path to decode
#     :returns: Decoded path
#     :raises: TypeError if wrong type given
#     """
#     if isinstance(filename, six.binary_type):
#         return filename.decode(encoding=sys.getfilesystemencoding())
#     if isinstance(filename, six.text_type):
#         return filename
# 
#     raise TypeError("Value is not a (byte) string")
# 
# def load_scraper_json(json_name):
#     """
#     Load scraper stream from JSON file.
# 
#     :json_name: JSON file name
#     :returns: Stream metadata from JSON file.
#     """
#     with open(json_name, 'rt') as json_file:
#         streams = json.load(json_file)
#     new_streams = {}
#     for index in streams:
#         new_streams[int(index)] = streams[index]
#         new_streams[int(index)]["index"] = \
#             int(new_streams[int(index)]["index"])
#     return new_streams
# 
# def read_md_references(workspace, ref_file):
#     """Read all the MD IDs as a dictionary.
# 
#     :workspace: path to workspace directory
#     :ref_file: Metadata reference file
#     :returns: A dict of references or None if reference file doesn't
#               exist
#     """
#     reference_file = os.path.join(workspace, ref_file)
# 
#     if os.path.isfile(reference_file):
#         references = {}
#         with open(reference_file) as in_file:
#             for line in in_file:
#                 references.update(json.loads(line))
#         return references
#     return None
# 
# Path: siptools/xml/mets.py
# NAMESPACES = {
#     'mets': 'http://www.loc.gov/METS/',
#     'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
#     'premis': 'info:lc/xmlns/premis-v2',
#     'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
#     'xlink': 'http://www.w3.org/1999/xlink',
#     'mix': 'http://www.loc.gov/mix/v20',
#     'ead3': 'http://ead3.archivists.org/schema/',
#     'addml': 'http://www.arkivverket.no/standarder/addml',
#     'audiomd': 'http://www.loc.gov/audioMD/',
#     'videomd': 'http://www.loc.gov/videoMD/'
# }


# Path: tests/scripts/test_import_object.py
import datetime
import io
import os.path
import pytest
import six
import lxml.etree as ET
from siptools.scripts import import_object
from siptools.utils import fsdecode_path, load_scraper_json, read_md_references
from siptools.xml.mets import NAMESPACES

# encoding: utf-8
"""Unit tests for ``siptools.scripts.import_object`` module."""
from __future__ import unicode_literals






def get_amd_file(path,
                 input_file,
                 stream=None,
                 ref_file='import-object-md-references.jsonl',
                 suffix='-PREMIS%3AOBJECT-amd.xml'):
    """Get id."""

    refs = read_md_references(path, ref_file)