#!/usr/bin/python

#------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
# 
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence. 
# You may obtain a copy of the Licence at:
# 
# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf
# 
# Unless required by applicable law or agreed to in 
# writing, software distributed under the Licence is 
# distributed on an "AS IS" basis, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. 
# See the Licence for the specific language governing 
# permissions and limitations under the Licence.
#------------------------------------------------------------------------------

import os
import sys
import getopt
from wnodes.cli.utils import load_config
from wnodes.cli.utils import get_config
from wnodes.cli.utils import checks 
from wnodes.cli.commands import list_occi
 
class ListImages:
    '''A command-line program to list images.'''
    def __init__(self):
        self.conf = (False,'wnodes-cli.cfg')
        self.all_paths = False
        self.verbose = False

    def __usage(self):
        print ("Usage: wnodes_list_images [OPTION]\n"+
            "Request to shows information of all the images associated to the user\n\n"+
            "OPTION\n"+
            "  -c, --conf=CONF_FILE     specifies a customized conf filename\n"+
            "  -a,--allpath             enable the print of all path. The\n"+
            "                           default of which is %s\n"
            % self.all_paths +
            "  --verbose                show verbose information. The\n"+
            "                           default of which is %s.\n"
            % self.verbose +
            "  -h, --help               display this help and exit.\n"+
            "  -v, --version            output version information and exit.\n")

    def __parse(self):
        try:
            opts, args = getopt.getopt(sys.argv[1:], \
                "havc:", ["help", "allpaths", "verbose", "version", "conf="])
        except getopt.GetoptError, err:
            print str(err) 
            self.__usage()
            sys.exit(2)

        for key, value in opts:
            if key in ("-h", "--help"):
                self.__usage()
                sys.exit()
            elif key in ("-c", "--conf"):
                self.conf = (True, value)
            elif key in ("-a", "--allpaths"):
                self.all_paths = True
            elif key == "--verbose":
                self.verbose = True
            elif key in ("-v", "--version"):
                self.version = __import__('cli').get_release()
                sys.exit()
            else:
                raise errors.OptionError("unhandled option")

    def doWork(self):
        self.__parse()

        if not self.conf[0]:
            config_file = \
                get_config.ConfigurationFileLocation(\
                    file_name = self.conf[1]).get_configuration_file()
        else:
            config_file = \
                get_config.ConfigurationFileLocation(\
                    file_name = self.conf[1]).get_custom_configuration_file()

        load_user_data = load_config.LoadUserConfig(\
            config_file = config_file).load_user_data()

        if self.all_paths:
            obj = list_occi.ListImages(\
                user_data=load_user_data, path='-/')
        else:
            obj = list_occi.ListImages(\
                user_data=load_user_data, path='compute/')
        
        if self.verbose:
            print obj.get_command()

        value,msg = obj.get_output()

        if msg == '':
            for x in value:
                if 'Location: ' in x:
                    msg_location = '% Total    % Received % Xferd'
                    if msg_location not in x:
                        print x.split('Location: ')[1]
        else:
            print msg

if __name__ == '__main__':
    try:
        a = ListImages()
        a.doWork()
    except get_config.NoFileFound, err:
        print '\n\nExecution: ', err
    except get_config.NoPathFound, err:
        print '\n\nExecution: ', err
    except load_config.WrongConfigurationFile, err:
        print '\n\nExecution: ', err
    except load_config.WrongConfigurationSettings, err:
        print '\n\nExecution: ', err
    except checks.NoCmdFound, err:
        print '\n\nExecution: ', err
    except list_occi.ListImageError, err:
        print '\n\nExecution: ', err
    except KeyboardInterrupt:
        print '\n\nExecution n!'
        sys.exit(1)
