package seng302.Model;

import seng302.Data.BoatData;
import seng302.Data.RaceData;
import seng302.Data.RegattaData;
import seng302.DataInput.RaceDataSource;
import seng302.DataInput.RegattaDataSource;
import seng302.Exceptions.InvalidBoatDataException;
import seng302.Exceptions.InvalidRaceDataException;
import seng302.Exceptions.InvalidRegattaDataException;
import seng302.MockOutput;

import java.io.IOException;


/**
 * Created by esa46 on 21/04/17.
 */
public class Event {

    RaceDataSource raceDataSource;
    RegattaDataSource regattaDataSource;

    MockOutput mockOutput;

    public Event(RaceDataSource raceData, RegattaDataSource regattaData) {
        this.raceDataSource = raceData;
        this.regattaDataSource = regattaData;
        try {
            mockOutput = new MockOutput();
            new Thread(mockOutput).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Send the initial race data and then begin race simulation
     */
    public void start() {
        System.out.println("Sending Regatta");
        sendRegattaData();
        System.out.println("Sending Race");
        sendRaceData();
        System.out.println("Sending Boat");
        sendBoatData();

        int scaleFactor = 5;//TEMP - was 15.
        Race newRace = new Race(raceDataSource, scaleFactor, mockOutput);
        new Thread((newRace)).start();
    }


    /**
     * Send XML string of initial regatta data to the visualiser
     * @throws InvalidRegattaDataException Invalid regatta
     */
    public void sendRegattaData() throws InvalidRegattaDataException {

        System.setOut(System.out);
        RegattaData regattaData = new RegattaData(regattaDataSource);
        String xmlString = regattaData.createXML();
        mockOutput.setRegattaXml(xmlString);
        mockOutput.parseXMLString(xmlString, 26);

    }

    /**
     * Send XML string of initial race data to the visualiser
     * @throws InvalidRaceDataException Invalid race
     */
    public void sendRaceData() throws InvalidRaceDataException {
        RaceData raceData = new RaceData(raceDataSource);
        //Serialize race data to an XML as a string.
        String xmlString = raceData.createXML();
        mockOutput.setRaceXml(xmlString);
        mockOutput.parseXMLString(xmlString, 26);
    }

    /**
     * Send XML string of initial boat data to the visualiser
     * @throws InvalidBoatDataException Invalid boat
     */
    public void sendBoatData() throws InvalidBoatDataException {
        BoatData boatData = new BoatData(raceDataSource.getBoats());
        //Serialize race data to an XML as a string.
        String xmlString = boatData.createXML();
        mockOutput.setBoatsXml(xmlString);
        mockOutput.parseXMLString(xmlString, 26);

    }

}
