import { PLATFORM_WIDHT, PLATFORM_HEIGHT, PLAT_TYPE, PLATFORMS_GAP, GAME_COLORS } from './constants.js';
import { addTypeSpecifics, selectPlatformType } from './platformTypes.js';

function createPlatform(x, y, elevation, type, startingPlatform = false) {
    const platform = new Sprite();

    platform.x = x;
    platform.y = y;
    platform.elevation = elevation;

    platform.w = startingPlatform ? width - 10 : PLATFORM_WIDHT;
    platform.h = PLATFORM_HEIGHT;

    platform.collider = 'static';
    platform.bounciness = 0;
    platform.type = type;

    addTypeSpecifics(platform, type);

    return platform;
}

function generateNewPlatforms(platforms, currentHighestPlat) {
    let spawnY = currentHighestPlat.y - PLATFORMS_GAP;
    let i = 0;
    while (spawnY > 0) {
        i++;
        const elevation = currentHighestPlat.elevation + i * PLATFORMS_GAP;
        const newPlat = createPlatform(
            random(PLATFORM_WIDHT / 2, width - PLATFORM_WIDHT / 2),
            spawnY,
            elevation,
            selectPlatformType(elevation),
        );
        platforms.add(newPlat);
        spawnY -= PLATFORMS_GAP;
    }
    platforms.bounciness = 0;

    return platforms;
}


export function moveWorld(platforms, elevation, move) {
    let highestPlat = null;
    for (let i = platforms.length - 1; i >= 0; i--) {
        const plat = platforms[i];
        plat.y += move;
        if (plat.y >= height) {
            plat.remove();
            continue;
        }
        if (!highestPlat || plat.y < highestPlat.y) {
            highestPlat = plat;
        }
    }

    if (highestPlat.y > 0) {
        platforms = generateNewPlatforms(platforms, highestPlat);
    }
    return platforms;
}


export function initPlatforms() {
    let platforms = new Group();
    const startingPlat = createPlatform(width / 2, height - 10, 0, PLAT_TYPE.BASIC, true);
    startingPlat.color = GAME_COLORS.startingPlat;
    platforms.add(startingPlat);
    let plarform1 = createPlatform(width / 4*3, height - PLATFORMS_GAP, PLATFORMS_GAP, PLAT_TYPE.BASIC);
    platforms.add(plarform1);
    let plarform2 = createPlatform(width / 4, height - PLATFORMS_GAP*2, PLATFORMS_GAP*2, PLAT_TYPE.BASIC);
    platforms.add(plarform2);

    generateNewPlatforms(platforms, plarform2);
    return platforms;
}

