#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Python URL shortener on the command line with focus on code simplicity."""

import argparse
import sys

from clipdb import importDb, exportDb
from clipurl import shortenUrl, expandUrl



def parseArgs(args):
	parser = argparse.ArgumentParser(
		description="Python URL shortener on the command line with focus on code simplicity.")
	parser.add_argument('URL', action="store", nargs = '*',
		help="URLs to shorten or expand.")	
	parser.add_argument("-e", "--expand", action="store_true", default=False, 
		help="expand URL from a previously generated short URL.") 

	parser.add_argument("-i", "--input", dest="inputFilename",
		help="read URLs from an input file instead of the command line. One url by line.") 	

	parser.add_argument("--short-url-prefix",  default="http://cl.ip/",
		help="short URLs generated begin with. Default to http://cl.ip/") 	

	parser.add_argument("--key-length", type=int, default="10",
		help="generated key length. Default to 10") 	
	parser.add_argument("--key-base", type=int, default="62", choices=range(2, 65), metavar="[2-64]", 
		help="generated key base. Range from 2 (binary) to 64 (urlsafe). 62 is strict alphanumeric [0-9A-Za-z]. Default to 62.") 
	parser.add_argument("--key-algo",  choices=['sha', 'random'], default="sha",
		help="algorithm used to generate key. Default to sha.") 

	parser.add_argument("--db-name", default="clip.db", 
		help="filename to use for persistance database. Default to clip.db") 	
	parser.add_argument("--db-reset", action="store_true", default=False,
		help="Ignore existing db. Restart from empty db.") 


	config = parser.parse_args(args)

	# Get input urls from arguments of from file
	urls = config.URL
	if( config.inputFilename):
		with open(config.inputFilename) as f:
			urls = f.readlines()
			urls = [x.strip() for x in urls]  

	return  (urls, config)

def test_parseArgs():
	#Test  basic  arguments processing
	config = parseArgs(['http://example.com/'])
	assert(config.expand == False)

	config = parseArgs(['-e', 'http://example.com/'])
	assert(config.expand == True)

	config = parseArgs(['--expand', 'http://example.com/'])
	assert(config.expand == True)

	return 

def main():
	# Parse command line options
	(urls, config) = parseArgs(sys.argv[1:])

	# Restore previously shorten urls
	if config.db_reset == False:
		importDb(config.db_name)
	else:
		sys.stderr.write("Info: reseting short url databse.\n")

	# Process each (shorten or expand) and print result
	for u in urls:
		if( config.expand):
			print expandUrl(u)
		else:
			print shortenUrl(u, 
				config.short_url_prefix,
				config.key_algo, 
				config.key_base, 
				config.key_length)	
	
	# Save shorten url list
	exportDb(config.db_name)


if __name__ == '__main__' : main()