package de.frajul.endlessroll.entities;

import de.frajul.endlessroll.data.SynchronizedArrayList;
import de.frajul.endlessroll.data.Vector;
import de.frajul.endlessroll.entities.textures.Texture;

/**
 * Created by Julian on 20.07.2016.
 */
public class Background extends SynchronizedArrayList<Entity> {

    private final float PART_WIDTH = 5;
    private final float HALF_PART_WIDTH = PART_WIDTH / 2;
    private final float HEIGHT = 2.5f;
    private Texture texture;

    public Background(Texture texture) {
        this.texture = texture;
        super.add(createPart(-HALF_PART_WIDTH));
    }

    public void changeTexture(Texture texture) {
        this.texture = texture;
        synchronized (this) {
            for (Entity entity : this)
                entity.setTexture(texture);
        }
    }

    private Entity createPart(float xLeftEdge) {
        return new Entity(texture, new Vector(xLeftEdge + HALF_PART_WIDTH, (HEIGHT - 2) / 2), PART_WIDTH, HEIGHT);
    }

    public void move(float x, float cameraX) {
        Vector movement = new Vector(x, 0);
        synchronized (this) {
            for (Entity part : this)
                part.move(movement);
        }
        if (!super.isEmpty()) {
            Entity last = super.get(super.size() - 1);
            if (last.getRightEdge() - cameraX < 3) {
                super.add(createPart(last.getRightEdge() - 0.001f));
            }
            if (super.get(0).getRightEdge() - cameraX < -3) {
                super.remove(0);
            }
        }
    }

    public void resetPosition() {
        super.clear();
        super.add(createPart(-HALF_PART_WIDTH));
    }

}
