/*  OpenTally: Open-source election vote counting
 *  Copyright © 2021 Lee Yingtong Li (RunasSudo)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use crate::election::Election;
use crate::numbers::Number;

use itertools::Itertools;

use std::io::{BufWriter, Write};

/// Write the [Election] into BLT format
pub fn write<W: Write, N: Number>(election: Election<N>, output: W) {
	let mut output = BufWriter::new(output);
	
	// Writer header row
	output.write_fmt(format_args!("{} {}\n", election.candidates.len(), election.seats)).expect("IO Error");
	
	// Write withdrawn candidates
	if !election.withdrawn_candidates.is_empty() {
		output.write(election.withdrawn_candidates.into_iter().map(|idx| format!("-{}", idx + 1)).join(" ").as_bytes()).expect("IO Error");
		output.write(b"\n").expect("IO Error");
	}
	
	// Write ballots
	for ballot in election.ballots {
		output.write_fmt(format_args!("{}", ballot.orig_value)).expect("IO Error");
		
		for preference in ballot.preferences {
			output.write_fmt(format_args!(" {}", preference.into_iter().map(|p| p + 1).join("="))).expect("IO Error");
		}
		
		output.write(b" 0\n").expect("IO Error");
	}
	
	output.write(b"0\n").expect("IO Error");
	
	// Write candidate names
	for candidate in election.candidates {
		output.write_fmt(format_args!("\"{}\"\n", candidate.name)).expect("IO Error");
	}
	
	// Write election name
	output.write_fmt(format_args!("\"{}\"\n", election.name)).expect("IO Error");
}
