package seng302.Model;

import org.xml.sax.SAXException;
import seng302.DataInput.*;
import seng302.Exceptions.StreamedCourseXMLException;
import seng302.MockOutput;
import seng302.Networking.Messages.Enums.MessageType;

import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.text.ParseException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;


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

    String raceXML;
    String regattaXML;
    String boatXML;
    Polars boatPolars;
    MockOutput mockOutput;

    public Event(String raceXML, String regattaXML, String boatXML, Polars boatPolars) {

        this.raceXML = getRaceXMLAtCurrentTime(raceXML);
        this.boatXML = boatXML;
        this.regattaXML = regattaXML;
        this.boatPolars = boatPolars;
        try {
            mockOutput = new MockOutput();
            new Thread(mockOutput).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Sends the initial race data and then begins race simulation
     */
    public void start() {
        try {
            sendXMLs();
            Race newRace = new Race(new RaceXMLReader(this.raceXML, new BoatXMLReader(boatXML, this.boatPolars)), mockOutput);
            new Thread((newRace)).start();

        } catch (ParserConfigurationException | IOException | SAXException | ParseException | StreamedCourseXMLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Sends out each xml string, via the mock output
     */
    private void sendXMLs() {

        mockOutput.setRegattaXml(regattaXML);
        mockOutput.parseXMLString(regattaXML, MessageType.XMLMESSAGE.getValue());

        mockOutput.setRaceXml(raceXML);
        mockOutput.parseXMLString(raceXML, MessageType.XMLMESSAGE.getValue());

        mockOutput.setBoatsXml(boatXML);
        mockOutput.parseXMLString(boatXML, MessageType.XMLMESSAGE.getValue());
    }

    /**
     * Sets the xml description of the race to show the race was created now, and starts in 3 minutes
     * @param raceXML
     * @return String containing edited xml
     */
    private String getRaceXMLAtCurrentTime(String raceXML) {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        ZonedDateTime creationTime = ZonedDateTime.now();
        return raceXML.replace("CREATION_TIME", dateFormat.format(creationTime))
                .replace("START_TIME", dateFormat.format(creationTime.plusMinutes(3)));
    }

}
