#!/usr/bin/env python
'''
The MIT License (MIT)

Copyright (c) <2018> <Mathias Lesche>

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.

contact: mat.lesche(at)gmail.com
'''

''' python libraries '''
import logging

import datetime

from os.path import getmtime
from os.path import basename
from os.path import isfile
from os.path import isdir
from os.path import join as pathjoin

from os import chmod
from os import sep

from sys import _getframe as getframe

from subprocess import check_call

from types import NoneType

''' pipeline modules '''
from database.database import Database

from support.auxiliary_module import getLogfile

from support.information import Information
from support.main_logger import MainLogger

class 
(object):
  def __init__(self, db):
    self.__db = db
    self.__logger = logging.getLogger('dsp.database.archive_flowcell')

  def show_log(self, level, message):
    if level == 'debug':
      self.__logger.debug(message)
    elif level == 'info':
      self.__logger.info(message)
    elif level == 'warning':
      self.__logger.warning(message)
    elif level == 'error':
      self.__logger.error(message)
    elif level == 'critical':
      self.__logger.critical(message)

  def find_machinename(self, machinedf, machineid):
    try:
      m = [i for i in machinedf if i['ID'] == machineid][0]
    except IndexError:
      m = {'NAME' : 'no name', 'CODE' : 'no code'}
    return m

  def run_archive(self):
    dircount, notcount, archcount, isarchived, nd = 0, 0, 0, 0, 0
    total = 0
    for pr in self.__db.query_BfxProjects():
      total += 1
      archdate = pr['ARCHIVING_DATE']
      rawpath = pr['PROJECT_PATH']
      if isinstance(rawpath, NoneType):
        archfilepath = ''
      else:
        rawpath = pr['PROJECT_PATH'].rstrip(sep).rstrip(' ').lstrip(' ')
        rawpath_arch = '{0}_archived'.format(rawpath)
        archfilepath = pathjoin(rawpath_arch, 'filelist.txt')
      
      if isfile(archfilepath):
        if isinstance(archdate, NoneType):
          date = datetime.datetime.fromtimestamp(getmtime(archfilepath))
          self.show_log('info', "update BFX{0} with archive status and date: {1}".format(pr['ID'], date.date()))
          self.__db.update_Archiving_into_BfxProjects(pr['ID'], str(date.date()))
          isarchived += 1
        else: archcount += 1
      elif isinstance(rawpath, NoneType): notcount += 1      
      elif isdir(rawpath): dircount += 1
      else: nd += 1
    
    if archcount != 0: self.show_log('info', '{0} projects have already a date'.format(archcount))
    if isarchived != 0: self.show_log('info', '{0} projects have a new archive date'.format(isarchived))    
    if dircount != 0: self.show_log('warning', '{0} projects have a directory but are not archived yet'.format(dircount))
    if notcount != 0: self.show_log('warning', '{0} projects do not have a directory at all'.format(notcount))
    if nd != 0: self.show_log('warning', '{0} projects are not accountable'.format(notcount))
    

if __name__ == '__main__':
  logfile = pathjoin(Information.LOGDIRECTORY, getLogfile(basename(getframe().f_code.co_filename.rstrip('.py'))))
  mainlog = MainLogger(True, False, logfile)

  db = Database(Information.DB_HOST, Information.DB_USER, Information.DB_PW, Information.DB)
  db.setConnection()

  archiveinst = Archive_Analysis(db)
  archiveinst.run_archive()

  db.commitConnection()
  db.closeConnection()
  mainlog.close()
  logging.shutdown()
  
  if mainlog.fileh:
    check_call(['gzip', logfile])
    chmod(logfile+'.gz', 0664)
Archive_Analysis