#! python
# -*- coding: utf-8 -*-
'''
    PyResizeImage: Resize images, and pad them to give an exact size image
    Copyright (C) 2013  Alkatron, (alkatron@gmail.com)

    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 3 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, see <http://www.gnu.org/licenses/>.
'''

import os, getopt, sys, logging
from pyrszimg.core import resize_dir
from pyrszimg import VVERSION, read

# create logger with 'spam_application'
lggr = logging.getLogger(sys.argv[0])
lggr.setLevel(logging.INFO)
# create console handler 
ch = logging.StreamHandler()
# create formatter and add it to the handlers
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
lggr.addHandler(ch)

def hdr():
    msg="PyResizeImage %s  Copyright (C) 2013  Alkatron\n" % (VVERSION)
    msg+="This program comes with ABSOLUTELY NO WARRANTY; for details use -w options.\n"
    msg+="This is free software, and you are welcome to redistribute it\n"
    msg+="under certain conditions; use -w options for details.\n"
    msg+='-'*75
    print msg

def usage():
    print read('README.txt')

def main(argv=['-h']):
    _source=''
    _size=[]
    _dst=''
    _frmts=[]
    hdr()
    try:                                
        opts, args = getopt.getopt(argv, "i:o:s:f:wh", ["input=",'output=','size=','formats=']) 
    except getopt.GetoptError:           
        usage()                          
        sys.exit() 
    if not opts:
        usage()
        sys.exit() 
    for opt, arg in opts: 
        if opt in ('-i', '--input'):                
            _source= arg
            if not os.path.isdir(_source):
                lggr.error('Folder: %s .Not found!!! exit....'%(_source))
                #myerr( 'ERROR:\nFolder: %s .Not found!!!'%(_source))
                sys.exit() 
        elif opt in ('-o', '--output'):
            _dst= arg
            if not os.path.isdir(_dst):
                _answ=''
                while _answ not in ('y','n'):
                    _answ=raw_input( 'Folder: %s .not found!!! Do you want to create it (y/n)?'%(_dst))
                if _answ=='n':
                    sys.exit() 
        elif opt in ('-h'):
            usage()
            sys.exit() 
        elif opt in ('-w'):
            print read('COPYING.txt')
            sys.exit() 
        elif opt in ('-s', '--size'):
            _size=arg
        elif opt in ('-f', '--formats'):
            _frmts=arg
        else:
            print "Not a valid option" 
            usage()
            sys.exit() 
    if _source and _size:
        imgs=resize_dir(_source, _size, _dst, _frmts)
        _msg='-'*75
        _msg+='\n%i images converted - %i skipped' % (imgs['total']-imgs['skipped'],imgs['skipped'])
        _msg+='\nfrom: %s' % (_source,)
        _msg+='\nto: %s' % (imgs['path_to'],)
        _msg+='\nSize: %s - Formats: %s' % (_size, _frmts,)
        print _msg
    else:
        usage()

# def myerr(_msg):
#     hdr()
#     print _msg
    
if __name__ == '__main__':
    #_par=['-w']
#    _par=['-i', '/mnt/host/project/dprado/mbfoto/padded',
#         '-o', '/mnt/host/project/dprado/mbfoto/padded/pino', 
#         '-s','640/640', 
#         '-f','jpg/gif'
#         ]
#    main(_par)
    main(sys.argv[1:])
