#!/usr/local/bin/python3
import time
import logging
import argparse
import platform

import cup
import cup.exceptions

if __name__ == '__main__':
    parent_parser = argparse.ArgumentParser(description='CLI tool for Cup (Custom Unpacker-Packer)')
    parent_parser.add_argument('-l', '--logs',
                               help='output logs to a file')

    subparsers = parent_parser.add_subparsers(dest='subparser', title='available commands')

    parser_pack = subparsers.add_parser('pack')
    parser_pack.add_argument('paths',
                             nargs='+',
                             help='the files/directories to archive')
    parser_pack.add_argument('-o', '--output-file',
                             required=True,
                             help='the path where the archive will be created')

    parser_unpack = subparsers.add_parser('unpack')
    parser_unpack.add_argument('renaming',
                               nargs='*',
                               help='optional variable length argument used for file renaming or exact file extraction,'
                                    ' the type is FILE_NAME[=NEW_FILE_NAME]')
    parser_unpack.add_argument('-i', '--input-file',
                               required=True,
                               help='the input archive')
    parser_unpack.add_argument('-o', '--output-dir',
                               default='.',
                               help='the path to the directory where to unpack the archive, by default the current '
                                    'directory')

    parser_info = subparsers.add_parser('info')
    parser_info.add_argument('archive_path',
                             help='the path to the archive to get information about')

    args = parent_parser.parse_args()
    logs_filename = 'NUL' if platform.system().lower() == 'windows' else '/dev/null'
    if args.logs:
        logs_filename = args.logs
    logging.basicConfig(filename=logs_filename, level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(message)s')

    command = args.subparser
    try:
        if command == 'pack':
            cup.pack(*args.paths, archive_name=args.output_file)
        elif command == 'unpack':
            renaming = map(lambda rename: tuple(rename.split('=')), args.renaming)
            renaming = list(map(lambda rename: (rename[0], rename[0]) if len(rename) == 1 else rename, renaming))
            cup.unpack(*renaming, archive_path=args.input_file, destination_path=args.output_dir)
        elif command == 'info':
            archive_info = cup.info(args.archive_path)
            print(f"{'No':7}{'Size':12}{'Time of last file change':25}Path")
            for index, size, timestamp, path in archive_info:
                print(f'{str(index + 1):7}{str(size):12}{time.ctime(timestamp):25}{path}')
        else:
            parent_parser.print_usage()
    except cup.exceptions.CupException as ce:
        print(ce)
