#!/usr/bin/env python3
''' Command Line Interface - Sync Folders '''

import os
from timeit import default_timer as timer
import click
from folder import init_folder
from compare import FolderCompare

def validate_path(_, param, value):
    ''' Click argument validator - ensure arguments are directories '''
    if (param.name == 'destination') and folder_not_exists(value):
        click.echo('Destination folder not found. Creating: %s' % value)
        os.makedirs(value)
    if not os.path.isdir(value):
        msg = ''
        if os.path.isfile(value):
            msg = ' - %s is a file' % (value)
        raise click.BadParameter('%s needs to be a valid directory %s' % (param.name, msg))
    return value

def folder_not_exists(path):
    ''' Check if given path is not an existing file or folder '''
    return (not os.path.isfile(path)) and (not os.path.exists(path))

@click.command()
@click.option('--dry-run', is_flag=True)
@click.option('--overwrite/--no-overwrite', ' /-O', default=True)
@click.option('--ignore', '-i', multiple=True, type=str)
@click.option('--verbose', is_flag=True)
@click.argument('source', type=click.Path(exists=True), callback=validate_path, nargs=1)
@click.argument('destination', type=click.Path(), callback=validate_path, nargs=1)
# pylint: disable=too-many-arguments
def sync_folders(ignore, source, destination, overwrite, dry_run, verbose):
    """
    Sync the contents of source folder with destination.\n
    Essentially - backup the source to the destination.
    """
    if dry_run:
        click.secho('### Dry Run ###', fg='yellow', bold=True)

    click.echo('Syncing %s to %s' % (source, destination))

    if ignore:
        click.echo('Ignore files matching patterns: [%s]' % ', '.join(ignore))

    if overwrite:
        click.secho(
            'Warning: Conflicting destination files will be overwritten',
            bold=True,
            fg='red'
        )

    click.echo('Step 1/4: Generating metadata for %s' % source)
    start = timer()
    init_folder(source)
    end = timer()
    click.secho('Took %f seconds.' % (end - start), fg='yellow')

    click.echo('Step 2/4: Generating metadata for %s' % destination)
    start = timer()
    init_folder(destination)
    end = timer()
    click.secho('Took %f seconds.' % (end - start), fg='yellow')

    click.echo('Step 3/4: Computing diff between %s and %s' % (source, destination))
    start = timer()
    compare = FolderCompare(source, destination)
    compare.compute_diff(verbose=verbose)
    end = timer()
    click.secho('Took %f seconds.' % (end - start), fg='yellow')

if __name__ == '__main__':
    sync_folders() # pylint: disable=no-value-for-parameter
