import { PLAT_TYPE, GAME_COLORS, PLATFORM_WIDHT } from './constants.js';

function drawBasePlatform(platform) {
    fill(platform.color);
    stroke(0);
    strokeWeight(1);
    rect(0, 0, platform.w, platform.h, 15);
}

function drawSpringPlatform() {
    drawBasePlatform(this);

    fill(0);
    noStroke();
    textAlign(CENTER, CENTER);
    textSize(15);
    //textStyle(BOLD);
    text('⮝ ⮝ ⮝', 0, 2);
    textStyle(NORMAL);
}

function drawOneTimePlatform() {
    drawBasePlatform(this);

    stroke(0);
    strokeWeight(1.1);
    noFill();

    const drawCrack = (offsetX) => {
        beginShape();
        vertex(offsetX, -this.h * 0.45);
        vertex(offsetX - this.w * 0.08, -this.h * 0.1);
        vertex(offsetX + this.w * 0.08, this.h * 0.2);
        vertex(offsetX, this.h * 0.45);
        endShape();
    };

    drawCrack(-this.w * 0.25);
    drawCrack(0);
    drawCrack(this.w * 0.25);
}

function addMovingBehavior(platform) {
    platform.moveDir = random() < 0.5 ? -1 : 1;
    platform.moveSpeed = random(1, 2);
    platform.update = function () {
        this.x += this.moveDir * this.moveSpeed;
        if (this.x < PLATFORM_WIDHT / 2 || this.x > width - PLATFORM_WIDHT / 2) {
            this.moveDir *= -1;
        } 
    };
}



export function addTypeSpecifics(platform, type) {
    switch (platform.type) {
        case PLAT_TYPE.MOVING:
            platform.color = GAME_COLORS.movingPlat;
            platform.draw = function () {
                drawBasePlatform(this);
            };
            addMovingBehavior(platform);
            break;

        case PLAT_TYPE.SPRING:
            platform.color = GAME_COLORS.springPlat;
            platform.draw = drawSpringPlatform;
            break;

        case PLAT_TYPE.ONE_TIME:
            platform.color = GAME_COLORS.oneTimePlat;
            platform.draw = drawOneTimePlatform;
            break;

        default:
            platform.color = GAME_COLORS.basicPlat;
            platform.draw = function () {
                drawBasePlatform(this);
            };
            break;
    }
}

export function selectPlatformType(elevation) {
    const r = random();
    switch (true) {
        case elevation >= 800 && r < 0.15:
            return PLAT_TYPE.MOVING;
        case elevation >= 2000 && r < 0.30:
            return PLAT_TYPE.SPRING;
        case elevation >= 4000 && r < 0.45:
            return PLAT_TYPE.ONE_TIME;
        default:
            return PLAT_TYPE.BASIC;
    }
}