#  Copyright (C) 2019 The authors of Py-ChemShell
#
#  This file is part of Py-ChemShell.
#
#  Py-ChemShell is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation, either version 3 of the
#  License, or (at your option) any later version.
#
#  Py-ChemShell 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 Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with Py-ChemShell.  If not, see
#  <http://www.gnu.org/licenses/>.


def init(args):
    '''Initialise the platform specifications'''

    # nothing to do on Fedora 


def setup(args):
    '''Platform specifications for setup'''

    selectcases = {
                    # mpi_lib_path, mpi_include_path, and mpiexec
                    'openmpi':{ 'mpi_lib_path'    :'/usr/lib64/openmpi/lib',
                                'mpi_include_path':'/usr/lib64/openmpi/include',
                                'mpiexec'         :'mpirun',
                                'scalapack_flags' :'-lscalapack' 
                                },
                  }


    if args.__CHEMSH_ARCH == 'gnu':
        # correct the default value in `setup` if not overridden by the user
        args.__setarg('blas'        , '/usr/lib64')
        args.__setarg('lapack'      , '/usr/lib64')
        #args.__setarg('fftw'        , '/usr/lib64')
        #args.__setarg('fftw_include', '/usr/include')
        if ('scalapack' in args and not args.scalapack) or 'scalapack' not in args:
            args.scalapack = '/usr/lib64/openmpi/lib'

        # default MPI implementations: OpenMPI --mpi
        #                              MPICH   --mpi=mpich
        if args.mpi:
            if args.mpi in selectcases.keys():
                args.mpi, args.mpidist = True, args.mpi
            # assign the default values if not done by the user
            for arg in [ 'mpiexec', 'mpi_lib_path', 'mpi_include_path', 'scalapack_flags' ]:
                if not getattr(args, arg):
                    args.__setarg(arg, selectcases[getattr(args, 'mpidist', 'openmpi')][arg])


def run(args):
    ''''''

    from os import path

    platfmodule = args.__import('platforms', path.join(args.__CHEMSH_ROOT, 'chemsh', 'utils', 'platforms', '__init__.py'))

    nprocs = max(args.nprocs, args.nworkgroups)

    # if np=0 or np=1 run in serial; if np>1 run in parallel
    selectcases = { 0:platfmodule.runSerial,
                    1:platfmodule.runSerial }

    # force runSerial if built in serial (mpiexec is '')
    if not args.mpiexec:
        nprocs = 1

    selectcases.get(nprocs, platfmodule.runParallel)(args)


