# -*- coding: utf-8 -*-
"""command line tool

`jspcap.__main__` was originally the module file of
[`jspcapy`](https://github.com/JarryShaw/jspcapy), which
is now deprecated and merged with `jspcap`.

"""
import argparse
import os
import sys
import warnings

from jspcap.foundation.extraction import Extractor
from jspcap.interface import TREE, JSON, PLIST


# version number
__version__ = '0.5.0'


def get_parser():
    parser = argparse.ArgumentParser(prog='jspcapy', description=(
        'PCAP file extractor and formatted exporter'
    ))
    parser.add_argument('-V', '--version', action='version', version=f'{__version__}')
    parser.add_argument('fin', metavar='input-file-name',
                        help=(
                            'The name of input pcap file. If ".pcap" omits, '
                            'it will be automatically appended.'
                        ))
    parser.add_argument('-o', '--output', action='store', metavar='file-name',
                        dest='fout', help=(
                            'The name of input pcap file. If format extension '
                            'omits, it will be automatically appended.'
                        ))
    parser.add_argument('-f', '--format', action='store', metavar='format',
                        dest='format', help=(
                            'Print a extraction report in the specified output '
                            'format. Available are all formats supported by '
                            'jsformat, e.g.: json, plist, and tree.'
                        ))
    parser.add_argument('-j', '--json', action='store_true', default=False,
                        help=(
                            'Display extraction report as json. This will yield '
                            '"raw" output that may be used by external tools. '
                            'This option overrides all other options.'
                        ))
    parser.add_argument('-p', '--plist', action='store_true', default=False,
                        help=(
                            'Display extraction report as macOS Property List '
                            '(plist). This will yield "raw" output that may be '
                            'used by external tools. This option overrides all '
                            'other options.'
                        ))
    parser.add_argument('-t', '--tree', action='store_true', default=False,
                        help=(
                            'Display extraction report as tree view text. This '
                            'will yield "raw" output that may be used by external '
                            'tools. This option overrides all other options.'
                        ))
    parser.add_argument('-a', '--auto-extension', action='store_true', default=False,
                        help=(
                            'If output file extension omits, append automatically.'
                        ))
    parser.add_argument('-v', '--verbose', action='store_false', default=True,
                        help=(
                            'Show more information.'
                        ))
    parser.add_argument('-F', '--files', action='store_true', default=False,
                        help=(
                            'Split each frame into different files.'
                        ))
    parser.add_argument('-E', '--engine', action='store', dest='engine', choises=[
                        'default', 'jspcap', 'dpkt', 'scapy', 'pyshark',
                        ], default='default', metavar='PKG', help=(
                            'Indicate extraction engine. Note that except '
                            'default or jspcap engine, all other engines '
                            'need support of correspoding packages.'
                        ))
    parser.add_argument('-P', '--protocol', action='store', dest='protocol',
                        default='null', metavar='PROTOCOL', help=(
                            'Indicate extraction stops after which protocol.'
                        ))
    parser.add_argument('-L', '--layer', action='store', dest='layer', choises=[
                        'None', 'Link', 'Internet', 'Transport', 'Application',
                        ], default='None', metavar='LAYER', help=(
                            'Indicate extract frames until which layer.'
                        ))
    return parser


def main():
    parser = get_parser()
    args = parser.parse_args()
    warnings.simplefilter('ignore')

    if args.format:     fmt = args.format
    elif args.json:     fmt = JSON
    elif args.plist:    fmt = PLIST
    elif args.tree:     fmt = TREE
    else:               fmt = None

    extractor = Extractor(store=False, format=fmt,
                            fin=args.fin, fout=args.fout,
                            auto=args.verbose, files=args.files,
                            layer=args.layer, protocol=args.protocol,
                            engine=args.engine, extension=args.auto_extension)

    if not args.verbose:
        print(f"🚨 Loading file '{extractor.input}'")
        for frame in extractor:
            print(f' - Frame {extractor.length:>3d}: {extractor.protocol}')
        print(f"🍺 Report file{'s' if args.files else ''} stored in '{extractor.output}'")


if __name__ == '__main__':
    sys.exit(main())
