"""

gitdl - download github repositories easily!

Arguments:
   REPO   Repository to download

Usage:
  gitdl REPO
  gitdl -h | --help
  gitdl --version

 Options:
   -h --help    Show this message.
   --version    Show version
"""

import requests
import os
import zipfile
from docopt import docopt
from . import __version__

API_TOKEN = os.environ.get('GITHUB_API_TOKEN')


def get_params(API_TOKEN):
    """
    Set parameters of the request using GITHUB_API_TOKEN environment variable
    """
    if API_TOKEN is None:
        raise Exception('GITHUB_API_TOKEN not found')
    params = {'API_TOKEN': API_TOKEN}  # create a dict to be passed by request
    return params


def urlretrieve(url, path):
    """
    Retrieves a zipfile and writes it to a local disk
    """
    with open(path, 'wb') as f:
        r = requests.get(url, stream=True)
        for chunk in r.iter_content(1024):
            f.write(chunk)


def extractfiles(zipf):
    """
    Extract a zipfile to the current directory
    """
    with zipfile.ZipFile(zipf, "r") as z:
        z.extractall()


def get_first_search_result(resp):
    """
    Gets first search result from json response
    """
    try:
        first_result = resp['items'][0]
        return first_result
    except IndexError:
        raise Exception("Repository Not Found.")


def work_them_files(repo_name):
    """
    Extract, rename and delete.
    """
    extractfiles("{}.zip".format(repo_name))
    os.rename("{}-master".format(repo_name), "{}".format(repo_name))
    os.unlink("{}.zip".format(repo_name))


def main():

    args = docopt(__doc__, version=__version__)
    # send a GET to search url in GitHub API
    url = "https://api.github.com/search/repositories?q={}".format(args['REPO'])
    response = requests.get(url, params=get_params()).json()

    first_result = get_first_search_result(response)  # check for empty response

    download_url = first_result['html_url'] + '/archive/master.zip'
    repo_name = first_result['name']  # stores the repository name
    print(download_url)

    urlretrieve(download_url, "{}.zip".format(repo_name))

    work_them_files(repo_name)


if __name__ == "__main__":
    main()

@@ -104,20 +104,80 @@
   gitdl 
-REPO
+search %3CREPO%3E %5B--sort %3Cfield%3E ( --asc %7C --desc )%5D%0A  gitdl %3CREPO%3E
 %0A  gitdl
@@ -1613,24 +1613,136 @@
 po_name))%0A%0A%0A
+def print_results(response):%0A    items = response%5B'items'%5D%0A    for item in items:%0A        print(item%5B'name'%5D)%0A%0A%0A
 def main():%0A
@@ -1790,16 +1790,17 @@
 sion__)%0A
+%0A
     # se
@@ -1907,18 +1907,29 @@
 mat(
+%0A        
 args%5B'
+%3C
 REPO
+%3E
 '%5D)%0A
@@ -1979,16 +1979,25 @@
 _params(
+API_TOKEN
 )).json(
@@ -2007,46 +2007,96 @@
     
-first_result = get_first_search
+# if search is used, then print the results%0A    if args%5B'search'%5D:%0A        print
 _result
+s
 (res
@@ -2105,27 +2105,78 @@
 nse)
+%0A
   
-# check for empty
+  else:%0A        first_result = get_first_search_result(%0A           
  res
@@ -2180,18 +2180,23 @@
 response
+)
 %0A%0A
+    
     down
@@ -2255,16 +2255,20 @@
 er.zip'%0A
+    
     repo
@@ -2326,24 +2326,28 @@
 ry name%0A    
+ 
+   
 print(downlo
@@ -2355,16 +2355,20 @@
 d_url)%0A%0A
+    
     urlr
@@ -2418,16 +2418,20 @@
 name))%0A%0A
+    
     work

add search argument to search for repositories in github