#!/usr/bin/env python

import os
import logging
import argparse

from hubsync import github, workspace, sync, config as hubsync_config


LOG = logging.getLogger('hubsync')
LOG.setLevel(logging.INFO)
LOG.addHandler(logging.StreamHandler())


def validate_github_access(api):
    """Checks the user has access to github"""
    result = api.get(api.base_url)
    if result.get("message") == "Bad credentials":
        raise RuntimeError("Invalid credentials. Check your github token")

if __name__ == "__main__":
    config = hubsync_config.Config.from_ini_file('~/.hubsyncrc')
    parser = argparse.ArgumentParser(
        description="Keeps your repos in sync! Note: Reads defaults from"
                    " ~/.hubsyncrc",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--github_api_url', type=str,
                        required=not config.github.api_url,
                        default=config.github.api_url,
                        help="Base URL for the github instance.")
    parser.add_argument('--github_token', type=str,
                        required=not config.github.token,
                        default=config.github.token,
                        help="Private user token to get access to github")
    parser.add_argument('--ws_path', type=str,
                        required=not config.workspace.path,
                        default=config.workspace.path,
                        help="base path of your local workspace.")
    parser.add_argument('--logging', choices=['INFO', 'DEBUG', 'ERROR'],
                        required=False, default='INFO', type=str,
                        help="Logging level of the script")
    args = parser.parse_args()

    LOG.setLevel(args.logging)

    api_args = {
        "api_url": args.github_api_url,
        "user_token": args.github_token
    }

    github_api = github.Api(**api_args)
    local_workspace = workspace.Workspace(os.path.expanduser(args.ws_path))

    validate_github_access(github_api)

    print("Syncing '{}'".format(args.ws_path))
    sync_helper = sync.SyncHelper(github_api, config)
    sync_helper.sync(local_workspace, github_api)


