/*
 usage : java ModifList fileIn name mark [fileOut]
*/
package generated;

import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;

public class ModifList {
	private static ObjectFactory of; 
	private static JAXBContext jc;

	private static Studentlist readList(String fileIn) throws Exception {
		Unmarshaller unm = jc.createUnmarshaller();
		Studentlist ml = (Studentlist) unm.unmarshal(new File(fileIn));
		return ml;
	}// readList

	private static void out (Studentlist ml, String fileOut) throws Exception{
      	Marshaller mrs = jc.createMarshaller();
      	mrs.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      	
      	if( fileOut.length() != 0 ){
      		mrs.marshal(ml, new FileOutputStream(fileOut));
      	}else{
      		mrs.marshal(ml, System.out);
      	}
	}//out
	
	private static void modif(Studentlist ml, String name, Integer mark) throws Exception {  
		List<Studentlist.Student> lal =  ml.getStudent();
		Iterator<Studentlist.Student> it = lal.iterator();
		boolean found = false;
		while( it.hasNext() ){
			Studentlist.Student stud = it.next();
			if( stud.getName().equals(name) ){
				stud.setMark(mark);
				found = true;
				break;
			}
		}
		if( !found ){
			Studentlist.Student nstud = of.createStudentlistStudent();
			nstud.setName(name);
			nstud.setMark(mark);
			lal.add(nstud);
		}
	}//modif
	
	public static void main (String[] args) throws Exception{
		jc = JAXBContext.newInstance("generated");
		of = new ObjectFactory();
		
		String fileIn = args[0] ;
		String name = args[1];
		Integer mark = Integer.valueOf(args[2]);
		String fileOut = args.length == 4? args[3] : "";
		
		Studentlist ml = readList(fileIn);
		modif (ml, name, mark);
		out (ml, fileOut);
		System.out.println("Fatto !");
	}//main
}// class ModifList
			