#!/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 getopt
import sys
from wnodes.cli.utils import load_config
from wnodes.cli.utils import get_config
from wnodes.cli.utils import checks 
from wnodes.cli.utils import location
from wnodes.cli.commands import errors
from wnodes.cli.commands import list_occi
 
class ListImage:
    '''A command-line program to list images.'''
    def __init__(self):
        self.image_location = ''
        self.conf = (False,'wnodes-cli.cfg')
        self.verbose = False

    def __usage(self):
        print ("Usage: wnodes_list_image [OPTION] -l LOCATION\n"+
            "Request to show for the specified image the following information:\n"+
            "hostname, architecture, satus, cpu, and memory\n\n"+
            "OPTION\n"+
            "  -l,--location=LOCATION   specifies the location of the created\n"+
            "                           image. It is mandatory.\n"+
            "  -c, --conf=CONF_FILE     specifies a customized conf filename\n"+
            "  --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:], \
                "hvc:l:", ["help", "conf=", "location=", "verbose", "version"])
        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 ("-l", "--location"):
                self.image_location = value
            elif key == "--verbose":
                self.verbose = True
            elif key in ("-v", "--version"):
                self.version = __import__('cli').get_version()
                print self.version
                sys.exit()
            else:
                raise errors.OptionError("unhandled option")

        if not self.image_location:
            self.__usage()
            msg = ("Location not specified. Please use the option -l or" +
                " --location")
            raise errors.NoOptionSpecified(msg)

    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()

        location.LocationFormat(load_user_data, self.image_location)

        obj = list_occi.ListImage(\
            load_user_data, self.image_location)
        if self.verbose:
            print obj.get_command()

        value,msg = obj.get_output()

        if msg == '':
            info_image = {}
            for x in value:
                if 'occi.compute.hostname' in x:
                     info_image['hostname'] = x.split('occi.compute.hostname')[1][1:]
                elif 'occi.compute.architecture' in x:
                     info_image['architecture'] = x.split('occi.compute.architecture')[1][1:]
                elif 'occi.compute.cores' in x:
                     info_image['cores'] = x.split('occi.compute.cores')[1][1:]
                elif 'occi.compute.memory' in x:
                     info_image['memory'] = x.split('occi.compute.memory')[1][1:]
                elif 'occi.compute.state' in x:
                     info_image['state'] = x.split('occi.compute.state')[1][1:]
                elif 'occi.compute.speed' in x:
                     info_image['speed'] = x.split('occi.compute.speed')[1][1:]
            if len(info_image) > 0:
                list_occi.print_list_header()
                list_occi.print_image_details(info_image)
            else:
               raise list_occi.ListImageError('Details of image are not returned')
        else:
            print msg

if __name__ == '__main__':
    try:
        a = ListImage()
        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 errors.OptionError, err:
        print '\n\nExecution: ', err
    except errors.NoOptionSpecified, err:
        print '\n\nExecution: ', err
    except list_occi.ListImageError, err:
        print '\n\nExecution: ', err
    except list_occi.ListImageError, err:
        print '\n\nExecution: ', err
    except location.LocationFormatError, err:
        print '\n\nExecution: ', err
    except KeyboardInterrupt:
        print '\n\nExecution n!'
        sys.exit(1)
