#!/usr/bin/env python
# coding: utf-8
#
# Copyright © 2022 - Rennes Physics Institute
#
# This file is part of MsSpec-DFM.
#
# MsSpec-DFM 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 3 of the License, or
# (at your option) any later version.
# MsSpec-DFM 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 MsSpec-DFM.  If not, see <http://www.gnu.org/licenses/>.
#
# Source file  : src/python/msspec_dfm/version.py
# Last modified: Fri, 25 Feb 2022 17:27:32 +0100
# Committed by : Sylvain Tricot <sylvain.tricot@univ-rennes1.fr> 1645806435 +0100

import os
import sys
from tempfile import NamedTemporaryFile, TemporaryDirectory

from matplotlib import pyplot as plt
import numpy as np

from msspec_dfm.input_file import InputFile
from msspec_dfm.eps import epsilon

from contextlib import redirect_stdout

def compute(filename=None, folder=None, logfile='-', **parameters):
    # If filename is None, a temporary name is provided
    if filename is None:
        filename = NamedTemporaryFile().name
    
    # If folder is None, a temporary name is provided
    if folder is None:
        folder = TemporaryDirectory().name

    if logfile != '-':
        sys.stdout.flush()
        old_fd = os.dup(1)
        os.close(1)
        os.open(logfile, os.O_WRONLY|os.O_CREAT)

    data = {}
    input_file = InputFile(filename, **parameters)
    input_file.write()
    epsilon(filename, folder)
    for root, dirs, files in os.walk(folder):
        for f in files:
            data[os.path.splitext(f)[0]] = np.loadtxt(os.path.join(root, f))

    if logfile != '-':
        os.close(1)
        os.dup(old_fd)
        os.close(old_fd)

    return data
