
// Db Commons
use postgres::transaction::Transaction;
use failure::Error;

use game::{games_need_upkeep, game_update, game_write, game_delete};
use instance::{instances_need_upkeep, instance_update};
use net::{Db};

fn fetch_games(mut tx: Transaction) -> Result<Transaction, Error> {
    let games = games_need_upkeep(&mut tx)?;

    for mut game in games {
        let game = game.upkeep();
        match game_update(&mut tx, &game) {
            Ok(_) => (),
            Err(e) =>  {
                println!("{:?}", e);
                game_delete(&mut tx, game.id)?;
            }
        }
    }

    Ok(tx)
}

fn fetch_instances(mut tx: Transaction) -> Result<Transaction, Error> {
    let instances = instances_need_upkeep(&mut tx)?;

    for mut instance in instances {
        let (instance, new_games) = instance.upkeep();
        for game in new_games {
            game_write(&mut tx, &game)?;
        }
        instance_update(&mut tx, instance)?;
    }

    Ok(tx)
}

pub fn warden(db: Db) -> Result<(), Error> {
    fetch_games(db.transaction()?)?
        .commit()?;

    fetch_instances(db.transaction()?)?
        .commit()?;

    Ok(())
}