import { ENEMIES_CONFIG } from "./enemiesConfig.js";

export class Enemies {
    
    constructor(scene, type, x, y, path) {
        this.scene = scene;
        this.type = type;
        this.x = x;
        this.y = y;
        this.path = path;
        this.spread = ENEMIES_CONFIG[type].spread;
        this.speedLow = ENEMIES_CONFIG[type].speedLow;
        this.speedHigh = ENEMIES_CONFIG[type].speedHigh;
        this.baseSprite = ENEMIES_CONFIG[type].spriteStart;
        this.spawnRange = {
            low: 500,
            high: 8000
        }

        this.spawnEnemy();
    }

    spawnEnemy() {
        const randX = Phaser.Math.Between(-this.spread, this.spread);
        const randY = Phaser.Math.Between(-this.spread, this.spread);
        const randSpeed = Phaser.Math.Between(this.speedLow, this.speedHigh);
        const spawnX = (this.x * 200) + 100 + randX;
        const spawnY = (this.y * 200) + 100 + randY;

        // Randomize Spawn Time a bit
        this.scene.time.delayedCall(Phaser.Math.Between(this.spawnRange.low, this.spawnRange.high), () => {
            // Create enemy and store reference
            const enemy = this.scene.add.sprite(spawnX, spawnY, ENEMIES_CONFIG[this.type].spriteSheet, ENEMIES_CONFIG[this.type].spriteStart);
            
            // Create Animations
            this.createAnim('side', ENEMIES_CONFIG[this.type].spriteStart, ENEMIES_CONFIG[this.type].spriteStart+2);
            this.createAnim('up', ENEMIES_CONFIG[this.type].spriteStart+6, ENEMIES_CONFIG[this.type].spriteStart+7);
            this.createAnim('down', ENEMIES_CONFIG[this.type].spriteStart+3, ENEMIES_CONFIG[this.type].spriteStart+5);
            this.createAnim('die', ENEMIES_CONFIG[this.type].spriteStart+8, ENEMIES_CONFIG[this.type].spriteStart+9, 0);
            
            // Generate unique ID for enemy
            const uniqueId = Phaser.Math.Between(100000, 999999);

            enemy.props = {
                'offsetX': randX,
                'offsetY': randY,
                'path': this.path,
                'pathPhase': 0,
                'speed': randSpeed,
                'health': ENEMIES_CONFIG[this.type].health,
                'type': this.type,
                'distanceTraveled': 0,
                'id': uniqueId
            };

            this.scene.enemies.add(enemy);

            enemy.play(`${this.type}-side`);
        });
    }

    createAnim(type, start, end, repeat = -1) {
        if (!this.scene.anims.get(`${this.type}-${type}`)) {
            this.scene.anims.create({
                key: `${this.type}-${type}`,
                frames: this.scene.anims.generateFrameNumbers(ENEMIES_CONFIG[this.type].spriteSheet, { 
                    start: start, 
                    end: end, 
                }),
                frameRate: 5,
                repeat: repeat
            });
        }
    }
}