#!/usr/bin/python
import exceptions
import getopt
import sys
from wnodes import accounting
from wnodes.accounting import usage
from wnodes.accounting import record_format
from wnodes.accounting import message_format
from wnodes.accounting import requests

class ParsingError(exceptions.Exception):
    pass

class InputError(exceptions.Exception):
    pass

class Parser(object):

    def __init__(self):
        self.parameters = {}
        self.parameters['version'] = accounting.get_version()
        self.parameters['output_location'] = '.'
        self.parameters['ZoneName'] = 'EU'
        self.parameters['TimeZone'] = 'UTC'

    def __do_parsing__(self):
        try:
            opts, args = getopt.getopt(sys.argv[1:],
                "s:z:t:o:",
                ["help", "version",
                "sitename=", "zonename=", "timezone=", "outputlocation="])
        except getopt.GetoptError, err:
            print str(err)
            usage.get_usage(self.parameters)
            sys.exit(2)

        for opt, value in opts:
            if opt in ("--help"):
                usage.get_usage(self.parameters)
                sys.exit(0)
            elif opt in ("--version"):
                print self.parameters['version']
                sys.exit(0)
            elif opt in ("-s", "--sitename"):
                self.parameters['SiteName'] = value.strip()
            elif opt in ("-z", "--zonename"):
                self.parameters['ZoneName'] = value.strip()
            elif opt in ("-t", "--timezone"):
                self.parameters['TimeZone'] = value.strip()
            elif opt in ("-o", "--outputlocation"):
                self.parameters['output_location'] = value.strip()
            else:
                msg = 'The specified %s option is not recognized' % str(opt)
                raise ParsingError(msg)

    def __check_parameters__(self):
        try:
            if self.parameters['SiteName'] == '':
                 msg = ('The input %s cannot be empty. '
                     % 'SiteName'.lower() +
                     'Please use the option --help')
                 raise InputError(msg)
        except KeyError, err:
            msg = ('The input arguments are not provided. ' +
                'Please use the option --help')
            raise InputError(msg)

    def get_parameters(self):
        self.__do_parsing__()
        self.__check_parameters__()
        return self.parameters

if __name__ == '__main__':
   try:
       parameters = Parser().get_parameters()

       #set image_lists needs to be substitute with calls to the NS and CM
       #due to a temporary issue in the testbed the calls will be added later
       image_lists = [('vm0','Pending','cloud','cloud',0,0)]
       # DS: doc? what is this tuple supposed to mean?

       build_requests = requests.Requests()
       for request in image_lists:
           build_requests.add_request(request=request)

       records = []
       for image in build_requests.get_images():
           record = record_format.RecordFormat(SiteName=parameters['SiteName'],
               ZoneName=parameters['ZoneName'],
               TimeZone=parameters['TimeZone'],
               MachineName=image['MachineName'],
               Status=image['Status'],
               LocalUserId=image['LocalGroupId'],
               LocalGroupId=image['LocalGroupId'],
               StartTime=image['StartTime'],
               EndTime=image['EndTime'])
           records.append(record.get_information())

       build_message = message_format.MessageFormat(records_list=records)
       build_message.store_in_file(parameters['output_location'])

   except KeyError, err:
       print err, '\n'
   except InputError, err:
       print err, '\n'
   except ParsingError, err:
       print err, '\n'
   except requests.RequestsError, err:
       print err, '\n'
   except MessageStoreError, err:
       print err, '\n'
   except KeyboardInterrupt:
       print '\n\nExecution n!'
       sys.exit(1)
