package helowars;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

/**
 * For moving background image left to right in a loop.
 * @author Adarshkumar Pavani
 */

public class Background {

    // background image
    private BufferedImage image;

    //background scroll speed
    private double speed;

    // Positions of background
    private double xPositions[];
    private int yPosition;


    /**
     * Initialize objects for moving image.
     * @param image image object that will be moving.
     * @param speed speed and direction of movement
     * @param yPosition y coordinate of the image.
     */
    public void Initialize(BufferedImage image, double speed, int yPosition)
    {
        this.image = image;
        this.speed = speed;

        this.yPosition = yPosition;

        //calculating the number of times to render the image
        int numberOfPositions = (Framework.frameWidth / this.image.getWidth()) + 2; //adding 2 to avoid blank spaces
        xPositions = new double[numberOfPositions];

        // setting x coordinate for each image to be rendered
        for (int i = 0; i < xPositions.length; i++)
        {
            xPositions[i] = i * image.getWidth();
        }
    }


    /**
     * moving the images.
     */
    private void Update()
    {
        for (int i = 0; i < xPositions.length; i++)
        {
            // Move image
            xPositions[i] += speed;

            // if image moving left
            if (speed < 0)
            {
                // if image is out of the screen, it moves it to the end pixel column of image
                if (xPositions[i] <= -image.getWidth())
                {
                    xPositions[i] = image.getWidth() * (xPositions.length - 1);
                }
            }
            // if image moving right
            else
            {
                // if image is out of the screen, it moves it to the end pixel column of image
                if (xPositions[i] >= image.getWidth() * (xPositions.length - 1))
                {
                    xPositions[i] = -image.getWidth();
                }
            }
        }
    }

    /**
     * to render background images on the screen.
     * @param g2d Graphics2D
     */
    public void Draw(Graphics2D g2d)
    {
        this.Update();
        
        for (int i = 0; i < xPositions.length; i++)
        {
            g2d.drawImage(image, (int)xPositions[i], yPosition, null);
        }
    }
}