#!/usr/bin/env python3

import subprocess
import sys
from argparse import ArgumentParser

def print_image(filename, printer_name, num_copies):
    convert_cmd = [
        "convert", filename, "-background", "white", "-alpha", "remove", "-"
    ]
    lp_cmd = ["lp", "-d", printer_name, "-n", str(num_copies)]

    convert = subprocess.Popen(convert_cmd, stdout=subprocess.PIPE)
    lp = subprocess.Popen(
            lp_cmd,
            stdin=convert.stdout,
            stdout=subprocess.PIPE,
            encoding="utf-8")
    convert.stdout.close() # Allow `convert` to receive a SIGPIPE if `lp` exits.
    output = lp.communicate()[0]

    return output

def valid(printers, choice):
    return choice > 0 and choice <= printers.length

def new_current_file():
    return {"copies": 1}

def list_printers():
    lpstat_lines = subprocess.check_output(["lpstat", "-p"], encoding="utf-8").strip().split("\n")
    printer_list = list(map(lambda x: x.split(" ")[1], lpstat_lines))
    return printer_list

def get_printer_choice(printers):
    actual_choice = 0
    if len(printers) > 1:
        print("Available printers:")
        for (idx, printer) in enumerate(printers):
            print("{}. {}".format(idx + 1, printer))
        print("Which printer should be used? ")
        choice = 0
        for line in sys.stdin:
            print(line)
        actual_choice = choice - 1
    return printers[actual_choice]

def pluralize(n, singular, plural):
    if n == 1:
        return singular
    else:
        return plural

def main():
    argparser = ArgumentParser(description="print files from the command line")
    argparser.add_argument("files",
                           nargs="+",
                           help="file(s) to print")
    argparser.add_argument("--copies",
                           default=1,
                           type=int,
                           nargs="?",
                           help="number of copies to print")
    args = argparser.parse_args()
    printer = get_printer_choice(list_printers())
    copy_str = pluralize(args.copies, "copy", "copies")

    print("Printer: {}".format(printer))
    print("Copies:  {}".format(args.copies))
    print("")
    print("Files:")

    for filename in args.files:
        print("- {}".format(filename))
        print(print_image(filename, printer, args.copies))

if __name__ == '__main__':
    main()
