#!/usr/bin/python

# This is called copy_one instead of copy to avoid name conflicts with
# the Python standard library.

import nilmtools.filter
import nilmdb.client
from nilmdb.client.numpyclient import NumpyClient
import numpy as np
import sys

def main(argv = None):
    f = nilmtools.filter.Filter()
    parser = f.setup_parser("Copy a stream")
    parser.add_argument('-n', '--nometa', action='store_true',
                        help="Don't copy or check metadata")

    # Parse arguments
    try:
        args = f.parse_args(argv)
    except nilmtools.filter.MissingDestination as e:
        print("Source is %s (%s)" % (e.src.path, e.src.layout))
        print("Destination %s doesn't exist" % (e.dest.path))
        print("You could make it with a command like:")
        print("  nilmtool -u %s create %s %s" % (e.dest.url,
                                                 e.dest.path, e.src.layout))
        raise SystemExit(1)

    # Copy metadata
    if not args.nometa:
        meta = f.client_src.stream_get_metadata(f.src.path)
        f.check_dest_metadata(meta)

    # Copy all rows of data using the faster Numpy interfaces
    extractor = NumpyClient(f.src.url).stream_extract_numpy
    inserter = NumpyClient(f.dest.url).stream_insert_numpy_context
    for i in f.intervals():
        print("Processing", i.human_string())
        with inserter(f.dest.path, i.start, i.end) as insert_ctx:
            for data in extractor(f.src.path, i.start, i.end):
                insert_ctx.insert(data)

if __name__ == "__main__":
    main()
