#!/usr/bin/env python
#
# @package      hubzero-submit-client
# @file         submit
# @author       Steven Clark <clarks@purdue.edu>
# @copyright    Copyright (c) 2012-2015 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2012-2015 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#
import os
import sys
import logging

LOGDIRECTORY      = os.getcwd()
HUBLOGFILE        = '.submit.log'
APPLICATIONLOGGER = logging.getLogger('')

CONFIGURATIONDIRECTORY = os.path.join(os.sep,'etc','submit')
CONFIGURATIONFILE      = 'submit-client.conf'
CONFIGFILEPATH         = os.path.join(CONFIGURATIONDIRECTORY,CONFIGURATIONFILE)

from hubzero.submit.LogMessage   import getLogIDMessage as getLogMessage, logSetMessageFile
from hubzero.submit.SubmitClient import SubmitClient

def openLogger(logDirectory,
               hubLogFile):
   class EmptyFilter(logging.Filter):
      """
      This is a filter which rejects empty messages

      """

      def filter(self,record):
         if record.getMessage() == "":
            emptyRecord = True
         else:
            emptyRecord = False

         return(not emptyRecord)

   APPLICATIONLOGGER.setLevel(logging.ERROR)

   if sys.stderr.isatty():
      logHandler = logging.StreamHandler(sys.stderr)
      logSetMessageFile(sys.stderr)
   else:
      hubLogPath = os.path.join(logDirectory,hubLogFile)
      logHandler = logging.FileHandler(hubLogPath)

   emptyFilter = EmptyFilter()
   logHandler.addFilter(emptyFilter)

   logFormatter = logging.Formatter('%(asctime)s %(message)s','[%a %b %d %H:%M:%S %Y]')
   logHandler.setFormatter(logFormatter)
   APPLICATIONLOGGER.addHandler(logHandler)


def client(configFilePath):
   submitClient = SubmitClient(configFilePath)

   if submitClient.configure():
      (parseCommandError,contactServer) = submitClient.parseCommandArguments()
      if not parseCommandError:
         if not submitClient.reportDebugOutput():
            logSetMessageFile(None)
         else:
            APPLICATIONLOGGER.setLevel(logging.DEBUG)
         if contactServer:
            submitClient.getUserAttributes()
            if submitClient.connectToServer():
               submitClient.run()
      else:
         submitClient.sendUserErrorNotification("Command line argument parsing failed.")
         sys.exit(1)
   else:
      submitClient.sendUserErrorNotification("submit configuration failed.")
      sys.exit(1)


if __name__ == '__main__':
   openLogger(LOGDIRECTORY,HUBLOGFILE)

   client(CONFIGFILEPATH)

   sys.exit(0)


