/*
 * Copyright (c) 2023 Frank Fischer <frank-fischer@shadow-soft.de>
 *
 * 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 3 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, see  <http://www.gnu.org/licenses/>
 */

mod problem;
pub use problem::Problem;

mod worker;
pub use worker::Worker;

mod msg;

pub use crate::mpi::problem::DistributedFirstOrderProblem;
use either::Either;
use log::debug;
use mpi::traits::*;
use mpi::Threading;
use serde::Serialize;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
    #[error("mpi initialization could not create a universe.")]
    NoUniverse,
}

/// Create a first order problem for usage with MPI.
///
/// The function returns either [`Problem`] or a [`Worker`] depending
/// on whether the current task is being run on the root node or some
/// worker node.
pub fn new_problem<P: DistributedFirstOrderProblem>(problem: P) -> Result<Either<Problem<P>, Worker<P>>, Error>
where
    P::Minorant: Serialize,
    P::Err: Serialize,
{
    let (universe, thr) = mpi::initialize_with_threading(Threading::Multiple).ok_or(Error::NoUniverse)?;
    let world = universe.world();
    let rank = world.rank();

    debug!(
        "Init universe [{}]: {:?} {:?}",
        rank,
        thr,
        mpi::environment::threading_support()
    );

    if rank == 0 {
        // root node, the main process
        Ok(Either::Left(Problem::new(universe, problem)))
    } else {
        Ok(Either::Right(Worker::new(universe, problem)))
    }
}
