#!/usr/bin/python

# This file is part of the Printrun suite.
#
# Printrun 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 3 of the License, or
# (at your option) any later version.
#
# Printrun 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 Printrun.  If not, see <http://www.gnu.org/licenses/>.

import time
import getopt
import sys

from printrun.printcore import printcore
from printrun.utils import setup_logging
from printrun import gcoder

if __name__ == '__main__':
    setup_logging(sys.stderr)
    baud = 115200
    loud = False
    statusreport = False

    from printrun.printcore import __version__ as printcore_version

    usage = "Usage:\n"+\
            "  printcore [OPTIONS] PORT FILE\n\n"+\
            "Options:\n"+\
            "  -b=BAUD_RATE, --baud=BAUD_RATE\n"+\
            "\t\t\tSet baud rate value. Default value is 115200\n"+\
            "  -s, --statusreport\tPrint progress as percentage\n"+\
            "  -v, --verbose\t\tPrint additional progress information\n"+\
            "  -V, --version\t\tPrint program's version number and exit\n"+\
            "  -h, --help\t\tPrint this help message and exit\n"

    args = sys.argv[1:]
    j=0
    if len(args) == 0:
        print "Error: Port and gcode file were not specified.\n"
        print usage
        sys.exit(1)
    for i in args:
        try:
            option,value = i.split('=')
        except:
            option = i
        if option in ('-b','--baud'):
            try:
                baud = int(value)
            except ValueError:
                print "ValueError:"
                print "\tFrom option '%s'" % i
                print "\tInvalid value '%s'" % value
                print "\tBAUD_RATE must be an integer\n"
                print usage
                sys.exit(1)
            # FIXME: This should output a more apropiate error message when
            #        not a good baud rate is passed as an argument
            #        if value <= 1000 or value > 225000:
        elif option in ('-s','--statusreport'):
            statusreport = True
        elif option in ('-v','--verbose'):
            loud = True
        elif option in ('-V','--version'):
            print "printrun "+printcore_version
            sys.exit(0)
        elif option in ('-h', '--help'):
            print usage
            sys.exit(0)
        elif option.startswith('-'):
            print "Error: Unknown option: '%s'\n" % option
            print usage
            sys.exit(1)
        else:
            break
        j =+ 1
    if (len(args) - j) == 0:
        print "Error: Port and gcode file were not specified.\n"
        print usage
        sys.exit(1)
    elif (len(args) - j) == 1:
        print "Error: Port or gcode file were not specified.\n"
        print usage
        sys.exit(1)
    elif (len(args) - j) > 2:
        print "Error: Too many arguments.\n"
        print usage
        sys.exit(1)
    else:
        port = args[j]
        filename = args[j+1]

    print "Printing: %s on %s with baudrate %d" % (filename, port, baud)
    p = printcore(port, baud)
    p.loud = loud
    time.sleep(2)
    gcode = [i.strip() for i in open(filename)]
    gcode = gcoder.LightGCode(gcode)
    p.startprint(gcode)

    try:
        if statusreport:
            p.loud = False
            sys.stdout.write("Progress: 00.0%\r")
            sys.stdout.flush()
        while p.printing:
            time.sleep(1)
            if statusreport:
                progress = 100 * float(p.queueindex) / len(p.mainqueue)
                sys.stdout.write("Progress: %02.1f%%\r" % progress)
                sys.stdout.flush()
        p.disconnect()
        sys.exit(0)
    except:
        p.disconnect()
