#!/usr/bin/python
#
# LLRepo - LightLang repository manager
# Copyright (C) 2007-2016 Devaev Maxim
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# apps/llrepo/src/llrepo.py.  Generated from llrepo.py.in by configure.


import sys
import os
import argparse

sys.path.append(os.path.join("/usr/lib64", "llrepo"))
import const
import cli
import local
import remote


##### Private methods #####
def localList(resource_type) :
	resources_dict = local.fetchResources([resource_type])
	if len(resources_dict[resource_type]) == 0 :
		print "No local resources\n"
		return

	rows_list = [["Resource", "Local size"]]
	for resource_name in sorted(resources_dict[resource_type].keys()) :
		rows_list.append([
				resource_name,
				cli.formatSize(resources_dict[resource_type][resource_name]["file_size"])
			])

	cli.printTable(rows_list)

def remoteList(resource_type) :
	local_resources_dict = local.fetchResources([resource_type])
	remote_resources_dict = remote.fetchResources([resource_type])
	if len(remote_resources_dict[resource_type]) == 0 :
		print "No remote resources\n"
		return

	rows_list = [["Resource", "Remote size", "Installed", "Local size"]]
	for resource_name in sorted(remote_resources_dict[resource_type].keys()) :
		rows_list.append([
				resource_name,
				cli.formatSize(remote_resources_dict[resource_type][resource_name][0]["file_size"]),
				( "Yes" if resource_name in local_resources_dict[resource_type] else "" ),
				( cli.formatSize(local_resources_dict[resource_type][resource_name]["file_size"])
					if resource_name in local_resources_dict[resource_type] else "" )
			])

	cli.printTable(rows_list)


###
def installResources(names_list, resource_type) :
	names_list = list(set(names_list))

	local_resources_dict = local.fetchResources([resource_type])
	remote_resources_dict = remote.fetchResources([resource_type])

	print "Analysis of the request..."

	count = 0
	size = 0
	while count < len(names_list) :
		if ( names_list[count] in local_resources_dict[resource_type] or
			not names_list[count] in remote_resources_dict[resource_type] ) :
			names_list.pop(count)
			continue
		size += remote_resources_dict[resource_type][names_list[count]][0]["file_size"]
		count += 1
	if count == 0 :
		print "No appropriate resources\n"
		return

	print "OK, %d resources to install (%s to download)" % (count, cli.formatSize(size))
	print "Continue? [y/n]:",
	answer = raw_input()
	print
	if not answer.lower().startswith("y") :
		return

	for names_list_item in names_list :
		remote.installResource(names_list_item, resource_type, remote_resources_dict)

	print

def removeResources(names_list, resource_type) :
	names_list = list(set(names_list))

	resources_dict = local.fetchResources([resource_type])

	print "Analysis of the request..."

	count = 0
	size = 0
	while count < len(names_list) :
		if not names_list[count] in resources_dict[resource_type] :
			names_list.pop(count)
			continue
		size += resources_dict[resource_type][names_list[count]]["file_size"]
		count += 1
	if count == 0 :
		print "No appropriate resources\n"
		return

	print "OK, %d resources to remove (%s)" % (count, cli.formatSize(size))
	print "Continue? [y/n]:",
	answer = raw_input()
	print
	if not answer.lower().startswith("y") :
		return

	for names_list_item in names_list :
		local.removeResource(names_list_item, resource_type)

	print


###
def help() :
	version()
	print ( "\n\t%(llrepo)s locallist <dicts|sounds>\n"
		"\t%(llrepo)s remotelist <dicts|sounds>\n\n"
		"\t%(llrepo)s install <dicts|sounds> <file1>[... <fileN>]\n"
		"\t%(llrepo)s remove <dicts|sounds> <file1>[... <fileN>]\n\n"
		"\t%(llrepo)s help\n"
		"\t%(llrepo)s version\n" % ({ "llrepo" : sys.argv[0] }) )

def version() :
	print "%s-%s, Copyright (C) 2007-2016 Devaev Maxim, %s" % (sys.argv[0], const.VERSION, const.DEVELOPER_MAIL)


##### Main #####
if __name__ == "__main__" :
	if len(sys.argv) == 1 :
		help()
		sys.exit(0)
	elif len(sys.argv) >= 2 :
		if sys.argv[1] in ("-h", "-help", "--help", "help") :
			help()
			sys.exit(0)
		elif  sys.argv[1] in ("-v", "-version", "--version", "version") :
			version()
			sys.exit(0)

	name = os.path.basename(sys.argv[0])
	parser = argparse.ArgumentParser(prog=name, description="", usage="%s <action> <object>" % (name), epilog="")
	parser.add_argument("action", action="store", choices=["locallist", "remotelist", "install", "remove"])
	parser.add_argument("object", action="store", choices=["dict", "dicts", "sound", "sounds"])
	options = parser.parse_args(sys.argv[1:3])

	if options.action == "locallist" :
		if options.object in ("dict", "dicts") :
			localList("dicts")
		elif options.object in ("sound", "sounds") :
			localList("sounds")

	elif options.action == "remotelist" :
		if options.object in ("dict", "dicts") :
			remoteList("dicts")
		elif options.object in ("sound", "sounds") :
			remoteList("sounds")

	elif options.action == "install" :
		if options.object in ("dict", "dicts") :
			installResources(sys.argv[3:], "dicts")
		elif options.object in ("sound", "sounds") :
			installResources(sys.argv[3:], "sounds")

	elif options.action == "remove" :
		if options.object in ("dict", "dicts") :
			removeResources(sys.argv[3:], "dicts")
		elif options.object in ("sound", "sounds") :
			removeResources(sys.argv[3:], "sounds")

