#!/usr/bin/python
# -*- coding: utf-8 -*-

# ***************************************************************************
# *   Copyright (C) 2015 by Pierre-Henri WUILLEMIN                          *
# *   {prenom.nom}_at_lip6.fr                                               *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU General Public License as published by  *
# *   the Free Software Foundation; either version 2 of the License, or     *
# *   (at your option) any later version.                                   *
# *                                                                         *
# *   This program is distributed in the hope that it will be useful,       *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU General Public License for more details.                          *
# *                                                                         *
# *   You should have received a copy of the GNU General Public License     *
# *   along with this program; if not, write to the                         *
# *   Free Software Foundation, Inc.,                                       *
# *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
# ***************************************************************************
from __future__ import print_function

import glob
import os
import sys
from datetime import datetime

from .utils import error, notif, setifyString, CrossPlatformRelPath, critic


def checkTests(current):
  cde = current['tests']
  if cde == "quick":
    if 'aGrUM' in current['targets']:
      current['tests']='all'
      current['modules']='BASE+BN+LEARNING'
      cde='all'

  alltests = allTests(setifyString(current['modules']))

  if cde == "all" or cde=='quick':
    return alltests
  elif cde == 'list':
    printTests(current)
    sys.exit(0)
  else:
    return checkTestList(current, alltests)


def checkAndWriteTests(current):
  writeTestList(checkTests(current))


def checkTestList(current, alltests):
  res = []
  for ss in setifyString(current['tests']):
    s = '/' + ss + 'TestSuite.h'
    name = ""
    for tryfile in alltests:
      if tryfile.endswith(s):
        name = tryfile
        break
    if name == "":
      if ss != "show" and ss!="quick":
        error('Test "src/testunits/[module]/' + ss + 'TestSuite.h" does not exist for the selected modules')
      printTests(current)
      sys.exit(1)
    else:
      res.append(name)
  return res


def writeTestList(l):
  l.sort(key=lambda s: s.split('/')[-1])
  today = datetime.now()
  f = open('src/testunits/testList.cmake', 'w')
  f.write("# file automatically generated by act\n")
  f.write("# " + today.strftime("%A, %d. %B %Y %H:%M") + "\n")
  f.write("# do not change it\n")
  f.write("set(AGRUM_TESTS \n  ")
  f.write("\n  ".join(l))
  f.write("\n)\n")
  f.close()
  f = open('src/testunits/testList.all', 'w')
  f.write("# file automatically generated by act\n")
  f.write("# " + today.strftime("%A, %d. %B %Y %H:%M") + "\n")
  f.write("# do not change it\n")
  f.write("set(AGRUM_TESTS \n  ")
  f.write("\n  ".join(l))
  f.write("\n)\n")
  f.close()


def allTests(moduleset):
  s = []

  for x in moduleset:
    s += [CrossPlatformRelPath(x, "src/testunits")
          for x in glob.glob('src/testunits/module_' + x.upper() + '/*TestSuite.h')]

  return s


def testNames(testsList):
  return [s.split('/')[-1].split("TestSuite")[0] for s in testsList]


def checkTestListCmake(current):
  if not os.path.exists('src/testunits/testList.cmake'):
    writeTestList(allTests(current['modules']))
  else:
    with open('src/testunits/testList.cmake') as f:
      content = f.readlines()

    res = []
    rewrite = False
    for line in content:
      if line[0:2] == "  ":
        s = line.strip()
        if not os.path.exists('src/testunits/' + s):
          notif('Test ' + s[:-11] + ' (src/testunits/' + s + ') does not exist => removing it from tests list')
          rewrite = True
        else:
          res.append(s)
    if rewrite:
      writeTestList(res)


def printTestsForModule(m):
  print("=" * (2 + len(m)))
  print(" " + m + " ")
  print("=" * (2 + len(m)))

  l = testNames(allTests(set([m])))

  w = max([len(x) for x in l])
  nbr = 80 / w
  i = 0
  for s in sorted(l):
    print(s.ljust(w), end="\t")
    i += 1
    if i > nbr:
      i = 0
      print("")
  if i != 0:
    print("")
  print("")


def printTests(current):
  for modul in setifyString(current['modules']):
    printTestsForModule(modul)
