#!/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.commands import errors
from wnodes.cli.commands import create_occi
 
class CreateImage:
    '''A command-line program to create a given image.'''
   
    def __init__(self):
        self.verbose = False
        self.parameters = {'size':'small',
            'number':1,
            'tag':'',
            'conf':(False,'wnodes-cli.cfg')}

    def __usage(self):
        print ("Usage: wnodes_create_image [OPTION] -t IMAGE_NAME\n"+
            "Request to instantiate a set of images with the same characteristic\n\n"+
            "OPTION\n"+
            "  -t,--imagetag=IMAGE_NAME specifies the image tag name. It is\n"+
            "                           mandatory.\n"+
            "  -s,--imagesize=SIZE      specifies the size of the image.\n"+
            "                           Supported values are:\n"+
            "                           - small\n"+
            "                           - medium\n"+
            "                           - large\n"+
            "                           - extralarge\n"+
            "                           Please look at System Guide doc for\n"+
            "                           more information. The default of\n"+
            "                           which is %s.\n"
            % self.parameters['size'] +
            "  --vo=VO_NAME             specifies the vo name.\n"+
            "  -b, --number=NUMBER      specifies how many times the specified\n"
            "                           image must be created. The default of\n"+
            "                           which is %s.\n"
            % str(self.parameters['number']) +
            "  -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:t:s:b:", \
                ["help", "version", "verbose", \
                 "conf=", "imagetag=", "imagesize=", "vo=", "number="])
        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.parameters['conf'] = (True, value)
            elif key in ("-b", "--number"):
                self.parameters['number'] = int(value)
            elif key in ("-t", "--imagetag"):
                self.parameters['tag'] = value
            elif key in ("-s", "--imagesize"):
                self.parameters['size'] = value
            elif key == "--vo":
                self.parameters['vo'] = value
            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")

        if self.parameters['tag'] == '':
            self.__usage()
            msg = ("Image tag not specified. Please use the option -t or" +
                " --imagetag")
            raise errors.NoOptionSpecified(msg)

        if self.parameters['size'] not in ('small', 'medium', 'large', 'extralarge'):
            self.__usage()
            raise errors.OptionError("Image size wrong")

    def doWork(self):
        self.__parse()

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

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

        obj = create_occi.CreateImage(\
            load_user_data, self.parameters)

        if self.verbose:
                print obj.get_command()

        count = 0
        location_image = {}
        while count < self.parameters['number']:
            res, msg = obj.get_output()
            location_image[count] = (res, msg)
            count += 1

        for key, value in location_image.iteritems():
            if value[1] == '':
                for x in value[0]:
                    if 'Location: ' in x:
                        print x.split('Location: ')[1]
                        break
            else:
                print value[1] 

if __name__ == '__main__':
    try:
        a = CreateImage()
        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 load_config.GeneralError, err:
        print '\n\nExecution: ', err
    except create_occi.CreateImageError, err:
        print '\n\nExecution: ', err
    except KeyboardInterrupt:
        print '\n\nExecution n!'
        sys.exit(1)
