import HeightControl from "../functions/robot_control/robot_high_control.js";
import { GameObjects, Math } from "phaser";
import Effects from "./Effects.js";


const enemy_attack_details = [{
    kick: {
        up: [3, 4],
        same_origin: [1],
        down: [],
    },
    shoot: {
        up: [],
        same_origin: [4],
        down: [],
    }
},
{
    kick: {
        up: [3, 4],
        same_origin: [1],
        down: [],
    },
    shoot: {
        up: [],
        same_origin: [4],
        down: [],
    }
},
{
    kick: {
        up: [],
        same_origin: [7, 8],
        down: [],
    },
    shoot: {
        up: [3, 6],
        same_origin: [1, 4],
        down: [2, 5],
    }
}]


//battle_mecha1_Attack
class BattleMechaRobots extends GameObjects.Sprite {
    constructor(scene, enemy_no, x, y, width, height, features) {
        super(scene, enemy_no, x, y, width, height, features);
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.enemy_no = enemy_no;
        this.scene = scene;
        this.alive = true;
        this.features = features;
        this.enemy = this.scene.matter.add.sprite(this.x + this.width / 2, this.y, "battle_mecha" + this.enemy_no + "_Walk_anims");
        this.enemy.setBody({
            type: 'rectangle',
            width: this.enemy.displayWidth * 3 /4,
            height: this.enemy.displayHeight * (3 / 4)
        })
        this.enemy.setOrigin(0.5,1 / 8 + 0.5);
        this.esikDeger = this.width;
        this.hurting = false;
        this.attacks = [];
        this.enemy.setFixedRotation();
        this.enemy.setFriction(0.005);
        this.enemy.setFrictionAir(0.02);
        this.enemy.setData('DangerForPlayer', false);

        this.situationAttack = 0;
        this.enemy.setData('JumpTimes', 0);
        this.features.forEach(feature => {

            let keyVal = Object.keys(feature);

            if (keyVal[0].includes("Attack")) {

                this.attacks.push(((feature)));
            } else {
                if (keyVal[0] === "name") {
                    this.name = feature[keyVal[0]];
                } else if (keyVal[0] === "type") {
                    this.enemyType = feature[keyVal[0]];
                } else if (keyVal[0] === "health") {
                    this.health = Number(feature[keyVal[0]]) ?? 100;
                    this.firstHealth = this.health;
                }
            }
        });



        this.scene.time.addEvent({
            delay: 750,
            callback: () => {
                if (this.alive == true) {
                    const shootPower = (this.targetEnemiesDistance / this.width) * 30;



                    if (this.targetEnemiesDistance < this.width) {
                        if (this.situationAttack == 0) {
                            this.scene.hurt(shootPower);
                        }

                        if (this.targetEnemiesDistance < this.width) {
                            this.attack(0);
                        } else {
                            this.attack(1);
                        }
                    } else {
                        this.enemy.setData('DangerForPlayer', false);
                    }



                    /*
                    
                                this.enemy.setData('DangerForPlayer',true);
                            } else {
                                this.enemy.setData('DangerForPlayer',false);
                                this.enemy.setData('isOnAttack',false);
                    
                    
                     */


                }

            },
            args: [],
            loop: true
        })








        this.ctx = this.scene.add.graphics();
        this.ctx.setDefaultStyles({
            fillStyle: {
                color: 0xff0000,
                alpha: 1
            },
            lineStyle: {
                width: 1,
                color: 0x0000ff,
                alpha: 0.75
            }
        });

        this.enemy.anims.play("battle_mecha" + this.enemy_no + "_Walk_anims");

        this.attackDetail = enemy_attack_details[this.enemy_no - 1];
    }

    loop() {

        if (this.healthBar || !this.alive) {
            this.healthBar.clear();
        }
        if (this.alive) {


            this.healthBar = this.ctx.fillRect(-this.enemy.width / 2, -this.enemy.height / 5, (this.health / this.firstHealth) * this.enemy.width, this.enemy.height / 10);

            this.healthBar.x = this.enemy.x;
            this.healthBar.y = this.enemy.y;

        }


        if (this.alive) {






            if (this.health <= 2.5) {
                new Effects(this.enemy.x, this.enemy.y, { name: "explodingEffectHigh" }, this.scene);
                this.death();


                //new Effects(this.enemy.x,this.enemy.y, { name: "explodingEffectHigh" }, this.scene);
            }

            const playerX = this.scene.player.x + this.scene.player.width / 2;
            const playerY = this.scene.player.y + this.scene.player.height / 2;
            const deltaX = playerX - this.enemy.x;
            const deltaY = playerY - this.enemy.y;

            this.situationAttack = HeightControl(deltaX, deltaY);
            if (this.enemy.getData('DangerForPlayer') == false) {
                if (deltaY > 0) {
                    this.animChange('FlyDown')
                } else if (deltaY < 0) {
                    this.animChange('FlyUp');
                }
            }

            if (this.enemy.flipX) {
                this.targetEnemiesDistance = Math.Distance.Between(playerX - this.scene.player.width / 2, playerY, this.enemy.x, this.enemy.y + this.enemy.height / 2);

            } else {
                this.targetEnemiesDistance = Math.Distance.Between(playerX + this.scene.player.width / 2, playerY, this.enemy.x + this.enemy.width / 2, this.enemy.y + this.enemy.height / 2);
            }

            if (this.targetEnemiesDistance < this.width) {
                if (playerX > this.enemy.x + this.enemy.width) {
                    this.enemy.setFlipX(false);
                } else if (playerX < this.enemy.x + this.enemy.width) {
                    this.enemy.setFlipX(true);
                }
            }


            if (this.targetEnemiesDistance < this.width / 2) {
                if (playerX < this.enemy.x + this.enemy.width / 2) {
                    this.move(-3);

                } else if (playerX > this.enemy.x + this.enemy.width / 2) {
                    this.move(3);

                }



            } else {
                this.Idle()
            }



        }

    }

    move(x) {

        if (this.hurting == false && this.enemy.getData('DangerForPlayer') == false) {
            this.animChange("Walk");
        }

        if (this.targetEnemiesDistance > 30) {
            this.enemy.setVelocityX(x);
        }

    }


    //"battle_mecha" + this.enemy_no + "_" + "_Walk_anims"
    animChange(Type) {
        if (this.alive == true && this.enemy.anims.currentAnim.key !== "battle_mecha" + this.enemy_no + "_" + Type + "_anims") {
            this.enemy.anims.play("battle_mecha" + this.enemy_no + "_" + Type + "_anims");
        }

    }
    hurt(x) {

        this.animChange("Hurt");
        this.hurting = true;
        this.jump(2)
        this.scene.time.addEvent({
            delay: 1000,
            args: [],
            callback: () => {
                if (this.enemy.getData('DangerForPlayer') == false) {
                    this.animChange("Idle");
                }

                this.hurting = false;
            }
        })




        this.health -= x;
        if (this.health < x) {
            this.health = 0;
        }
    }

    jump(x) {
        this.scene.checkCollision(this.enemy);
        if (this.enemy.getData('canJump') == true || this.enemy.getData("JumpTimes") < 1) {
            this.enemy.setVelocityY(-x);
            this.enemy.setData("JumpTimes", this.enemy.getData("JumpTimes") + 1);
        }

    }

    death() {
        if (this.hurting == true) {
            this.animChange("Death");

        }

        this.scene.player.setData('isGuilty', true);
        this.scene.police_siren = this.scene.sound.add('police_siren');
        /*
        if(this.scene.police_siren && this.scene.police_siren.isPlaying == false){
                this.scene.police_siren.play();
        }*/

        if (this.alive && this.enemy && this.enemy.anims && this.enemy.anims.currentFrame && this.enemy.anims.currentFrame.isLast) {

            this.alive = false;
            this.healthBar.clear();
            this.healthBar.destroy();
            this.enemy.destroy();
            this.scene.battle_mechas.splice(this.scene.battle_mechas.indexOf(this), 1);



        } else {
            this.alive = false;
            this.scene.time.addEvent({
                delay: 1000,
                args: [],
                callback: () => {

                    this.alive = false;
                    this.healthBar.clear();
                    this.healthBar.destroy();
                    this.enemy.destroy();
                    this.scene.battle_mechas.splice(this.scene.battle_mechas.indexOf(this), 1);
                }
            })


        }

    }
    Idle() {
        if (this.hurting == false && this.enemy.getData('DangerForPlayer') == false) {
            this.animChange('Idle')
        }

    }
    attack(type = 1) {
        this.enemy.setData('DangerForPlayer', true);
        if (this.hurting == false) {
            if (type == 0) {
                this.animChange("WalkAttack");
            } else if (type == 1) {

                this.animChange("Attack");
            }


        }




    }
}

export default BattleMechaRobots;

______



    update() {






        if (this.isMapLoaded) {


            if (isSocketWorks && isSocketWorks == true && socket) {

                socket.emit("getAllWithoutMe", { Id: myId });
            }






            if (this.healthBar) {
                this.healthBar.clear();
            }


            if (this.polices) {

                this.polices.forEach((police, key) => {
                    police.loop();
                    if (police.alive == false) {
                        this.polices.splice(key, 1);
                    }
                })
                if (this.polices.length <= 0) {
                    this.policeSpeech.stop();
                    if (this.police_siren) {
                        this.police_siren.stop();
                    }

                }
            }


            if (this.battle_mechas) {
                this.battle_mechas.forEach(battle_mecha => {
                    battle_mecha.loop();
                })
            }

            if (this.all_movers) {


                this.all_movers.forEach((mover, key) => {
                    const data = mover.getData('position_data');

                    if (data) {
                        const beforePos = data.before;
                        const nowPos = data.now;
                        const deltaX = nowPos.x - beforePos.x;
                        const deltaY = nowPos.y - beforePos.y;

                        this.real_mover[key].setVelocity(deltaX, deltaY)



                    }

                });
            }

if(this.player){
    if(this.player.anims.currentAnim.key !== "player_Azur_DoubleJump" && this.player.getData("JumpTimes") > 1){
this.player.anims.play("player_Azur_DoubleJump");
    }

}



            if (this.ladders) {
                this.currentTile = this.ladders.getTileAtWorldXY(...controlAllSquares(this.player.x, this.player.y))
            }

            function controlAllSquares(x, y) {
                return [Math.FloorTo(x / 32) * 32, Math.FloorTo(y / 32) * 32];
            }



            if (this.currentTile) {
                this.player.setData("canClimb", true);
            } else {

                this.player.setData("canClimb", false);
            }


            this.text.x = this.player.x;
            this.text.y = this.player.y;


            this.healthBar = this.ctx.fillRect(0, -this.player.height / 5, (this.player.getData("health") / this.player.getData("first_health")) * this.player.width, this.player.height / 10);

            this.healthBar.x = this.player.x - this.player.width / 2;
            this.healthBar.y = this.player.y - this.player.height / 3;








            if (this.isDesktop) {

                if (keyList.has(Keys().jump)) {
                    if (this.player.getData("canClimb")) {
                        if (this.player.anims.currentAnim.key !== 'player_Azur_Climb') {
                            this.player.anims.play("player_Azur_Climb")
                        }

                        this.Climb(this.player, 4);
                    }
                }


                if (this.player.anims.currentAnim.key !== "player_Azur_Idle" && !(keyList.has(Keys().left) || keyList.has(Keys().right) || keyList.has(Keys().jump))) {

                    if (!this.player.getData("isHurting") && !this.player.anims.currentAnim.key.includes("Hurt")) {
                        if (this.IsGunWith) {
                            this.player.anims.play("gun" + this.defaultGunNumber + "_Idle");
                        } else {
                            this.player.anims.play("player_Azur_Idle");
                        }

                    } else {
                        if (this.player.anims.currentAnim.frames[1].isLast) {


                            this.player.setData("isHurting", false);
                            if (this.player.getVelocity().x < 3.5 && this.player.getVelocity().x > -3.5) {


                                if (this.IsGunWith) {
                                    this.player.anims.play("gun" + this.defaultGunNumber + "_Idle");
                                } else if (this.player.anims.currentAnim.key !== "player_Azur_Idle") {
                                    this.player.anims.play("player_Azur_Idle");
                                }

                            }
                        }
                    }

                }
            } else {


                if (this.player.getVelocity().x > -3.5 && this.player.getVelocity().x < 3.5) {


                    if (this.IsGunWith) {
                        this.player.anims.play("gun" + this.defaultGunNumber + "_Idle");
                    } else if (this.player.anims.currentAnim.key !== "player_Azur_Idle") {
                        this.player.anims.play("player_Azur_Idle");
                    }

                }




            }


            this.workers.forEach((enemy, key) => {
                enemy.loop();
            })


            this.robots.forEach((enemy, key) => {

                enemy.loop();


            });






            if (this.player.y > this.deathLine.y) {


                if (this.canExit && this.canExit == true) {
                    this.SwitchWithAnims('WelcomeMenu-Great_job', {
                        sound: 'get_up_always'
                    });



                }
            }


            const yourTaken = Math.Distance.Between(this.keys.x, this.keys.y, this.player.x, this.player.y);

            const yourFinish = Math.Distance.Between(this.FinishCoord.x + this.FinishCoord.width / 2, this.FinishCoord.y + this.FinishCoord.height / 2, this.player.x, this.player.y);


            if (yourTaken < 40 && this.keyTaken == false) {


                this.keySound.play();



                this.keys.destroy();

                this.keyTaken = true;

            }



            if (yourFinish < (this.FinishCoord.width) && this.keyTaken) {
                if (!this.entry.anims.currentAnim) {
                    this.entry.anims.play("entry");


                    if (this.isWin == false) {
                        localStorage.setItem('level_number', Number(localStorage.getItem('level_number')) + 1);
                        this.isWin = true;
                        this.maskGraphics.fillStyle(0xff0000);
                        this.maskGraphics.setAlpha(0.5);
                        this.maskGraphics.fillCircle(0, 0, this.sys.game.config.width * 2 / 3);


                        this.lightMask = this.maskGraphics.createGeometryMask();
                        this.cameras.main.setMask(this.lightMask);

                    }

                }






                this.escaped = true;

                this.lockOpen.play();


                this.time.addEvent({
                    delay: 1000,
                    args: [],
                    callback: () => {
                        this.doorOpen.play();
                        if (this.canExit && this.canExit == true) {
                            this.SwitchWithAnims('WelcomeMenu-Great_job', {
                                effects: 'burst',
                                sound: 'victory'
                            });
                        }

                    }
                });







            }



            for (let i = this.bombs.length - 1; i >= 0; i--) {
                let bomb = this.bombs[i];
                if (bomb.getVelocity().x > 3 || bomb.getVelocity().x < -3) {
                    let currentDurance = bomb.getData("durance");
                    bomb.setMass(0.75);
                    bomb.setFriction(125);
                    const distanceForBombToMe = Math.Distance.Between(this.player.x, this.player.y, bomb.x, bomb.y);

                    if(distanceForBombToMe < 150){
                        this.hurt(Number(bomb.getData("perDamage")));
                    }
                   



                    this.workers.forEach(worker => {
                        const distanceForBomb = Math.Distance.Between(worker.enemy.x, worker.enemy.y, bomb.x, bomb.y);
                        if (distanceForBomb < 150) {
                            worker.hurt(5);
                            if (worker.health < 0) {
                                worker.death();

                            }
                        }
                    });



                    this.robots.forEach(robot => {
                        const distanceForBomb = Math.Distance.Between(robot.robot.x, robot.robot.y, bomb.x, bomb.y);
                        if (distanceForBomb < 150) {
                            robot.hurt(25);
                            if (robot.health < 1) {
                                robot.death();

                            }
                        }
                    });
                    bomb.setData("durance", currentDurance - 5);
                    new Effects(bomb.x, bomb.y, { name: "explodingEffectHigh" }, this);
                }

                if (bomb.getData("durance") < 0) {
                    new Effects(bomb.x, bomb.y, { name: "explodingEffectHigh" }, this);
                    this.bombs.splice(i, 1);
                    if (Math.Distance.Between(bomb.x, bomb.y, this.player.x, this.player.y) < 75) {
                        this.player.setData("health", this.player.getData("health") - 75)
                    }
                    bomb.destroy();

                }
            }





            if (keyList.has(Keys().shoot) && this.IsGunWith && this.player.getData('isCanShoot')) {
                this.shoot();

            }


            if (keyList.has("KeyX") && this.IsGunWith) {

            }



this.minSpeed = 1;
            if (!(keyList.has(Keys().left) && keyList.has(Keys().right))) {
                if(this.velocityCurrentLeft > 6){
                    this.velocityCurrentLeft = 6;
                }
                if(this.velocityCurrentRight > 6){
                    this.velocityCurrentRight = 6;
                }

         
                if (keyList.has(Keys().left)) {
                    this.velocityCurrentRight = this.minSpeed;
                    this.velocityCurrentLeft += 0.5;
                    this.move(this.player, -this.velocityCurrentLeft, 0);
                } else {
                    this.velocityCurrentLeft = this.minSpeed;
                }

                if (keyList.has(Keys().right)) {
                    this.velocityCurrentLeft = this.minSpeed;
                    this.velocityCurrentRight += 0.5;
                    this.move(this.player, this.velocityCurrentRight, 0);
                } else {
                    this.velocityCurrentRight = this.minSpeed;

                }

            }


            this.velocityCurrentLeft *= 0.95;
            this.velocityCurrentRight *= 0.95;
        /*
    if (!this.isDesktop) {

               // this.Joystick1.loop();

            }
        */


            let data = {
                anim: this.player.anims.currentAnim.key,
                x: this.player.x,
                y: this.player.y
                , velocity: {
                    x: this.player.getVelocity().x,
                    y: this.player.getVelocity().y
                },
                keyTaken: this.keyTaken,
                missionFinished: this.escaped,
                canJump: this.player.getData("canJump"),
                jumpTimes: this.player.getData("jumpTimes"),
                flipped: this.player.flipX
            };











            this.comminucateWith(data);



        }

    }


bana bunu eğer belli bir mesafede önünde engel varsa atlasın ama çok görmüyorsa da yani duvar varsa(bunu matterjs raycaster ı ile algılarsan iyi olur) o zaman da idle olsun

her vuruşta hurt ile birlikte hafif zıplasın(5-10px) kadar linearVelocity ile

ama dediğim gibi her şey daha gerçekçi olmalı