#!/usr/bin/python3

import os
import sys
import re
import argparse
import textwrap
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/..'))

import opi
from opi.plugins import PluginManager
from opi.version import __version__


class PreserveWhiteSpaceWrapRawTextHelpFormatter(argparse.RawTextHelpFormatter):
	def __add_whitespace(self, idx, iWSpace, text):
		if idx == 0:
			return text
		return (" " * iWSpace) + text

	def _split_lines(self, text, width):
		textRows = text.splitlines()
		for idx,line in enumerate(textRows):
			search = re.search('\s*[0-9\-]{0,}\.?\s*', line)
			if line.strip() == "":
				textRows[idx] = " "
			elif search:
				lWSpace = search.end()
				lines = [self.__add_whitespace(i,lWSpace,x) for i,x in enumerate(textwrap.wrap(line, width))]
				textRows[idx] = lines
		return [item for sublist in textRows for item in sublist]


try:
	pm = PluginManager()
	ap = argparse.ArgumentParser(
		formatter_class=PreserveWhiteSpaceWrapRawTextHelpFormatter,
		description=textwrap.dedent('''\
			openSUSE Package Installer
			==========================

			Search and install almost all packages available for openSUSE and SLE:
			  1. openSUSE Build Service
			  2. Packman
			  2. Popular packages for various vendors

		'''),
		epilog=textwrap.dedent('''\
			Also these queries can be used to install packages from various other vendors:
		''') + pm.get_plugin_string(' '*2))

	ap.add_argument('query', nargs='*', type=str, help=textwrap.dedent('''\
		can be any package name or part of it and will be searched for both at the openSUSE Build Service and Packman.
		If multiple query arguments are provided only results matching all of them are returned.
	'''))
	ap.add_argument('-v', '--version', action='version', version=('opi version ' +  __version__))

	args = ap.parse_args()

	if not args.query:
		ap.print_help()
		sys.exit()

	# Try to find a matching plugin for the query (and run it and exit afterwards)
	pm.run(args.query[0])

	binaries = []
	binaries.extend(opi.search_published_binary('openSUSE', args.query))
	binaries.extend(opi.search_published_binary('Packman', args.query))
	binaries = opi.sort_binaries(binaries)
	if len(binaries) == 0:
		print("No package found.")
		sys.exit()
	binary_names = opi.get_binary_names(binaries)

	# Print and select a package name option
	selected_name = opi.ask_for_option(binary_names)
	print("You have selected package name: %s" % selected_name)

	binary_options = opi.get_binaries_by_name(selected_name, binaries)

	# Print and select a binary package option
	selected_binary = opi.ask_for_option(binary_options, option_filter=opi.format_binary_option, disable_pager=True)
	print("You have selected binary package: %s" % opi.format_binary_option(selected_binary, table=False))
	if opi.is_personal_project(selected_binary['project']):
		print(opi.colored(
			"BE CAREFUL! The package is from a personal repository and NOT reviewed by others.\n"
			"You can ask the author to submit the package to development projects and openSUSE:Factory.\n"
			"Learn more at https://en.opensuse.org/openSUSE:How_to_contribute_to_Factory",
			'red'
		))

	# Install selected package
	opi.install_binary(selected_binary)
except KeyboardInterrupt:
	print()
