#!/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 delete_occi
from wnodes.cli.commands import list_occi
 
class DeleteImage:
    '''A command-line program to delete a given image.'''
    def __init__(self):
        self.image_location = ''
        self.verbose = False
        self.conf = (False,'wnodes-cli.cfg')

    def __usage(self):
        print ("Usage: wnodes_delete_image [OPTION] -l LOCATION\n"+
            "Request to delete an image that is in the ACTIVE state\n\n"+
            "OPTION\n"+
            "  -l,--location=LOCATION   specifies the location of the image\n"+
            "                           to be deleted. 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", "version", "verbose", "conf=", "location="])
        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_release()
                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 = delete_occi.DeleteImage(\
            load_user_data, self.image_location)
        if self.verbose: 
            print obj.get_command()

        value,msg = obj.get_output()

        if msg == '':
            if '\r' not in value:
                print value
        else:
            print msg
      

if __name__ == '__main__':
    try:
        a = DeleteImage()
        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 delete_occi.DeleteImageError, err:
        print '\n\nExecution: ', err
    except location.LocationFormatError, err:
        print '\n\nExecution: ', err
    except KeyboardInterrupt:
        print '\n\nExecution n!'
        sys.exit(1)
