#!/usr/bin/env python
# -*- coding: utf-8; mode: Python -*-
#
#
# Lars Jørgen Solberg <supersolberg@gmail.com> 2014
#
import argparse
from PIL import Image
import sys
import cStringIO

import shellpic

if __name__ == "__main__":
    
    # parse command line parameters
    parser = argparse.ArgumentParser()
    parser.add_argument("image", help="Use '-' to read from STDIN")
    parser.add_argument("--shell8", action="store_true", 
                        help="Print text suitable for a shell capable of displaying 8bit colors (default)")
    parser.add_argument("--shell24", action="store_true", 
                        help="Print text suitable for a shell capable of displaying 24bit colors")
    parser.add_argument("--irc", action="store_true", 
                        help="Print text suitable for piping to an irc client")
    parser.add_argument("--no-scale", action="store_true",
                        help="Do not attempt to scale the image to fit the terminal")
    parser.add_argument("--scale-x", nargs=1, type=int,
                        help="Scale the image to this width")
    parser.add_argument("--scale-y", nargs=1, type=int,
                        help="Scale the image to this height")
    args = parser.parse_args()

    # create the right kind of 'Formatter'
    if args.irc:
        formatter = shellpic.Irc()
    elif args.shell24:
        formatter = shellpic.Shell24Bit()
    else:
        formatter = shellpic.Shell8bit()
    dimentions = formatter.dimentions()
    
    # load the image
    if args.image == '-':
        # we need to copy the entire image to a buffer as PIL likes to seek()
        buf = cStringIO.StringIO()
        buf.write(sys.stdin.read())
        buf.seek(0)
        img = Image.open(buf)
        img.load() # so we can safely close buf
        buf.close()
    else:
        img = Image.open(args.image)

    # scale it to fit the terminal
    if not args.no_scale:
        if args.scale_x:
            dimentions = [args.scale_x[0], dimentions[1]]
        if args.scale_y:
            dimentions = [dimentions[0], args.scale_y[0]]
        img = shellpic.scale(img, *dimentions)
    
    # print the resutl to STDOUT
    text = formatter.format(img)
    print text.encode('utf-8')
