#!/usr/bin/env python3

import json
from pathlib import Path
import lzma

import click
import RigolWFM.wfm as rigol
import scipy


@click.command()
@click.argument('infile', type=click.Path(dir_okay=False, exists=True))
@click.argument('outfile', type=click.Path(dir_okay=False, path_type=Path), required=False)
@click.option('-f', '--factor', type=int, default=500, help='Downsampling factor')
def cli(infile, outfile, factor):
    if outfile is None:
        outfile = Path(infile).with_suffix('.lzjson')
    wf = rigol.Wfm.from_file(infile, 'DS1054Z')
    data = wf.channels[0].volts
    
    data = scipy.signal.decimate(data, factor, ftype='fir')[::-1]
    td = wf.channels[0].seconds_per_point * factor

    outfile.write_bytes(lzma.compress(json.dumps({'sample_interval_s': td, 'samples': list(data)}).encode()))

    
if __name__ == '__main__':
    cli()
