# @package      hubzero-submit-common
# @file         SubmissionScriptsInfo.py
# @copyright    Copyright (c) 2012-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2012-2020 The Regents of the University of California.
#
# 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 The Regents of the University of California.
#
import os.path
import re
import logging

from hubzero.submit.LogMessage import getLogJobIdMessage as getLogMessage

class SubmissionScriptsInfo:
   def __init__(self,
                requestor,
                submissionScriptRootPath=None,
                submissionScripts=None):
      self.logger = logging.getLogger(__name__)

      if   submissionScriptRootPath:
         self.submissionScripts = {}
         if os.path.exists(submissionScriptRootPath):
            if os.path.isdir(submissionScriptRootPath):
               for mode in ['Batch','Instant','Workflow']:
                  modePath = os.path.join(submissionScriptRootPath,requestor,mode)
                  if os.path.isdir(modePath):
                     self.submissionScripts[mode] = {}
                     dirDirectories = os.listdir(modePath)
                     reDirectories = re.compile("^[A-Z0-9]*$")
                     reFiles       = re.compile("^[a-z]*$")
                     matchingDirectories = list(filter(reDirectories.search,dirDirectories))
                     for submissionSystem in matchingDirectories:
                        self.submissionScripts[mode][submissionSystem] = {}
                        submissionSystemPath = os.path.join(modePath,submissionSystem)
                        dirFiles = os.listdir(submissionSystemPath)
                        matchingFiles = list(filter(reFiles.search,dirFiles))
                        for submissionScriptFile in matchingFiles:
                           submissionScriptPath = os.path.join(submissionSystemPath,submissionScriptFile)
                           try:
                              fpSubmissionScript = open(submissionScriptPath,'r')
                              try:
                                 lines = fpSubmissionScript.readlines()
                              except (IOError,OSError):
                                 self.logger.log(logging.ERROR,getLogMessage("Submission script %s could not be read" % \
                                                                                               (submissionScriptPath)))
                              else:
                                 self.submissionScripts[mode][submissionSystem][submissionScriptFile] = ''.join(lines)
                              finally:
                                 fpSubmissionScript.close()
                           except (IOError,OSError):
                              self.logger.log(logging.ERROR,getLogMessage("Submission script %s could not be opened" % \
                                                                                              (submissionScriptPath)))
            else:
               self.logger.log(logging.ERROR,getLogMessage("%s is not a directory" % (submissionScriptRootPath)))
         else:
            self.logger.log(logging.ERROR,getLogMessage("Submission script directory %s is missing" % (submissionScriptRootPath)))
      elif submissionScripts:
         self.submissionScripts = submissionScripts


   def getSubmissionScript(self,
                           mode,
                           submissionSystem,
                           jobType):
      try:
         batchSubmissionScript = self.submissionScripts[mode][submissionSystem][jobType]
      except:
         batchSubmissionScript = ""

      return(batchSubmissionScript)


   def getSubmissionScripts(self):
      return(self.submissionScripts)


