#!/usr/bin/env python

import os
import logging
import argparse
import ConfigParser

from hubsync import github, workspace, sync


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 = ConfigParser.ConfigParser(defaults={
        'api_url': 'https://api.github.com',
        'token': None,
        'path': os.getcwd()
    })
    config.read(os.path.expanduser('~/.hubsyncrc'))
    for section in ['github', 'workspace']:
        if not config.has_section(section):
            config.add_section(section)

    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.get('github', 'api_url'),
                        default=config.get('github', 'api_url'),
                        help="Base URL for the github instance.")
    parser.add_argument('--github_token', type=str,
                        required=not config.get('github', 'token'),
                        default=config.get('github', 'token'),
                        help="Private user token to get access to github")
    parser.add_argument('--ws_path', type=str,
                        required=not config.get('workspace', 'path'),
                        default=config.get('workspace', 'path'),
                        help="base path of your local workspace.")
    args = parser.parse_args()

    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)
    sync_helper.sync_all(
        workspaces=local_workspace.organizations,
        github_organizations=github_api.organizations
    )


