package seng302.Networking.MessageDecoders;

import seng302.Networking.Messages.CourseWind;

import java.util.ArrayList;
import java.util.Arrays;

import static seng302.Networking.Utils.ByteConverter.*;

/**
 * Created by hba56 on 23/04/17.
 */
public class CourseWindDecoder {
    byte messageVersionNumber;
    byte byteWindID;
    byte loopCount;
    ArrayList<CourseWind> loopMessages = new ArrayList();

    public CourseWindDecoder(byte[] encodedCourseWind) {
        final int lengthInBytesOfMessages = 20;

        messageVersionNumber = encodedCourseWind[0];
        byteWindID = encodedCourseWind[1];
        loopCount = encodedCourseWind[2];
        byte[] loopMessagesBytes = Arrays.copyOfRange(encodedCourseWind, 3, lengthInBytesOfMessages*loopCount+3);
        int messageLoopIndex = 0;

        for (int i=0; i < loopCount; i++) {
            byte[] messageBytes = Arrays.copyOfRange(loopMessagesBytes, messageLoopIndex, messageLoopIndex+20);
            ArrayList test = new ArrayList();
            byte[] windId = Arrays.copyOfRange(messageBytes, 0, 1);
            byte[] time = Arrays.copyOfRange(messageBytes, 1, 7);
            byte[] raceID = Arrays.copyOfRange(messageBytes, 7, 11);
            byte[] windDirection = Arrays.copyOfRange(messageBytes, 11, 13);
            byte[] windSpeed = Arrays.copyOfRange(messageBytes, 13, 15);
            byte[] bestUpwindAngle = Arrays.copyOfRange(messageBytes, 15, 17);
            byte[] bestDownwindAngle = Arrays.copyOfRange(messageBytes, 17, 19);
            byte[] flags = Arrays.copyOfRange(messageBytes, 19, 20);

            CourseWind message = new CourseWind(windId[0], bytesToLong(time),
                    bytesToInt(raceID), bytesToInt(windDirection),
                    bytesToInt(windSpeed), bytesToInt(bestUpwindAngle),
                    bytesToInt(bestDownwindAngle), flags[0]);

            loopMessages.add(message);
            messageLoopIndex += 20;
        }
    }

    public ArrayList<CourseWind> getLoopMessages() {
        return loopMessages;
    }

    public byte getMessageVersionNumber() {
        return messageVersionNumber;
    }

    public byte getByteWindID() {
        return byteWindID;
    }
}
