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

Copyright (c) <2016> <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 modules '''
import logging

from argparse import ArgumentParser as ArgumentParser
from argparse import RawDescriptionHelpFormatter

from collections import defaultdict
from collections import OrderedDict

from functools import partial

from operator import itemgetter

from os import chmod
from os import listdir

from os.path import join as pathjoin, basename, isfile

from types import NoneType
from types import TupleType
from types import IntType

''' own modules '''
from database.database import Database

from report.tex import Tex

from support.io_module import check_Directorylist
from support.io_module import check_Fileslist
from support.io_module import get_fileobject
from support.io_module import write_list

from support.information import Information

from support.main_logger import MainLogger

class Parser(object):
  def __init__(self):
    self.__parser = ArgumentParser(description="""
    Script builds a report tex file which includes the main plots
    and tables. pdfs have to be in the directory 'pdf' and
    tex files in the report folder and a file with the labels must
    exist. One can give the script tex prefix which is added to the input
    path in the tex files. Comes in handy when the report is copied
    and the structure is different.
    """, formatter_class=RawDescriptionHelpFormatter)
    self.initialiseParser()
    self.__report = ''
    self.__bfxid = ''
    self.__pdf = ''
    self.__tex = ''
    self.__species = []
    self.__ensembl = ''
    self.__config = ''
    self.__label = ''
    self.__programfile = ''
    self.__deresults = []
    
    self.__logger = logging.getLogger('dsp.report')
    self.parse()

  def initialiseParser(self):
    self.__parser.add_argument('-r', '--report', type=str, metavar='DIRECTORY', dest='report', required = True, help="report directory (contains tex files)")
    self.__parser.add_argument('-b', '--bfx', type=str, metavar='STRING', dest='bfx', required = True , help="bfx id of the project")
    self.__parser.add_argument('-d', '--deresults', type=str, metavar='DIRECTORY', dest='deresults', required = True, nargs='+', help="directories with de analysis files")
    self.__parser.add_argument('-l', '--labels', type=str, metavar='FILE', dest='label', required = True , help="label file (having labels for the tex figures and tables)")
    self.__parser.add_argument('-v', '--versionfile', type=str, metavar='FILE', dest='programfile', default='' , help="contains the used module versions")
    self.__parser.add_argument("-t", "--tex", dest = 'tex', metavar='STRING', default = '', help="tex prefix (added to the path of the  files within the tex document)")
    self.__parser.add_argument('-s', '--species', type=str, metavar='STRING', dest='species', default = 'mouse', help="species [human, mouse, zebrafish, rat, drosophila] (default: mouse)")
    self.__parser.add_argument('-e', '--ensembl', type=str, metavar='STRING', dest='ensembl', default = '81', help="Ensembl version (default: 81)")

  def parse(self, inputstring = None):
    if isinstance(inputstring, NoneType):
      self.__options = self.__parser.parse_args()
    else:
      self.__options = self.__parser.parse_args(inputstring)

  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)
  
  '''
  method check if the output directory exists
  @param inputdir: list
  @param inputparam: string representing the option
  @return: list
  '''
  def check_folder(self, inputdir, inputparam):
    good, bad = check_Directorylist(inputdir)
    if inputparam == '-r' and len(good) != 1:
      self.show_log('error', "check directory from {1} parameter: {0}".format(inputdir, inputparam))
      exit(2)
    elif inputparam == '-d' and len(bad) != 0:
      self.show_log('error', "check directory from {1} parameter: {0}".format(inputdir, inputparam))
      exit(2)
    return good

  '''
  method checks the input list which are files, filters for fastq files and returns the valid files 
  @param filelist: list of string
  @param choose: string with the option prefix
  @return: list or string
  '''
  def check_files(self, filelist, choose):
    if isinstance(filelist, NoneType):
      return []
    elif filelist[0] == '':
      return ''
    
    good = check_Fileslist(filelist)[0]