//
// Copyright(C) 2014-2015 Samuel Villarreal
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// DESCRIPTION:
//      Animal Script Object Classes
//

#include "scripts/animations.txt"

/*
==============================================================
GenericAnimal
==============================================================
*/

class GenericAnimal : ScriptObject
{
    kActor @self;
    float m_deathFreezeTime;
    float m_deathExplodeTime;
    GenericAnimal(kActor @actor)
    {
        @self = actor;
        m_deathFreezeTime = 0;
		m_deathExplodeTime = 0;
    }
    
    ~GenericAnimal()
    {
    }
    
    /*
    ==============================================================
    OnTick
    ==============================================================
    */
    
    void OnTick(void) {
        if((self.Flags() & AF_DEAD) != 0) {
            if(m_deathFreezeTime > 0) {
                m_deathFreezeTime -= GAME_DELTA_TIME;
                if (m_deathFreezeTime <= 0) {
                    Game.SpawnFx("fx/freeze_explosion.kfx", self.Origin(), self.SectorIndex());
                    self.Remove();
                }
            }
			if (m_deathExplodeTime > 0) {
                m_deathExplodeTime -= GAME_DELTA_TIME;
                if (m_deathExplodeTime <= 0) {
					self.PlaySound("sounds/shaders/explosion_2.ksnd");
                    Game.SpawnFx("fx/explosion_bits.kfx", self.Origin(), self.SectorIndex()); //bits
                    Game.SpawnFx("fx/generic_244.kfx", self.Origin(), self.SectorIndex()); //blood
                    self.Remove();
                }
			}
        }
    }
    
    /*
    ==============================================================
    OnDamage
    ==============================================================
    */
    
    void OnDamage(kActor @instigator, kDictMem @damageDef, const int damage)
    {
        bool bValue;
        
        if(damageDef is null)
        {
            return;
        }
        
        if(damageDef.GetBool("bAccelerator", bValue) && bValue == true) {
            self.AnimState().flags |= (ANF_PAUSED|ANF_NOINTERRUPT);
            m_deathFreezeTime = 3.0f;
            self.RunFxEvent("Enemy_Freeze");
            Game.SpawnFx("fx/freeze_start.kfx", self.Origin(), self.SectorIndex());
        } else if (damageDef.GetBool("bDeathExplode", bValue) && bValue == true) {
            self.AnimState().flags |= (ANF_PAUSED|ANF_NOINTERRUPT);
            m_deathExplodeTime = 0.01f;
            self.RunFxEvent("Enemy_Freeze");
            Game.SpawnFx("fx/freeze_start.kfx", self.Origin(), self.SectorIndex());
        }
    }
    
    /*
    ==============================================================
    OnSpawn
    ==============================================================
    */
    
    void OnSpawn(void)
    {
        self.Flags() |= AF_DEAD;
    }
};

/*
==============================================================
TurokAnimal
==============================================================
*/

class TurokAnimal : ScriptObject
{
    kActor @self;
    float thresholdTime;
    float turnOffset;
    float attackTime = 0.0f;
    TurokAnimal(kActor @actor)
    {
        @self = actor;
        thresholdTime = 0.0f;
    }
    
    ~TurokAnimal()
    {
    }
    
    /*
    ==============================================================
    CheckSight
    ==============================================================
    */
    
    bool CheckSight(void)
    {     
        float fov = self.GetTurnYaw(Player.Actor().Origin());      
        return (Math::Fabs(fov) <= 45.0f && self.CanSee(Player.Actor()));
    }

    void DoAttack() {
		self.SetTarget(Player.Actor().CastToActor());
		self.SpawnProjectile("fx/animalAcid.kfx", kVec3(0, 0, 50), self.GetTarget().Origin(), Math::Deg2Rad(45.0f));
	}
	
    void OnTick(void)
    {
		if (Debug::IsActorsDisabled()) {
			return;
		}
		
		if (Game.GetCurrentMapID() == 55) {
			if (attackTime > 0.0f) {
				attackTime -= GAME_DELTA_TIME;
				if (attackTime <= 0.0f) {
					attackTime = Math::RandRange(4.0f, 6.0f);
					DoAttack();
				}
			}
		}
		
        if(thresholdTime > 0.0f) {
            thresholdTime -= GAME_DELTA_TIME;
            
            kAngle an = -Player.Actor().Yaw() + Math::pi - turnOffset;
            
            float x = self.Origin().x + (Math::Sin(an) * 307.2f);
            float y = self.Origin().y + (Math::Cos(an) * 307.2f);
            
            kAngle newYaw = self.GetAvoidanceAngle(kVec3(x, y, self.Origin().z), 1.0f);
            
            self.Yaw() = (newYaw - self.Yaw()) * 0.05f + self.Yaw();
            
            if(thresholdTime <= 0.0f)
            {
                self.AnimState().Blend(anim_aiStanding, 4.0f, 8.0f, ANF_LOOP|ANF_ROOTMOTION);
            }
        }
        else
        {
            if((PlayLoop.Ticks() & 0x1F) != 0)
            {
                return;
            }
            
            if(self.Origin().DistanceSq(Player.Actor().Origin()) >= 262144.0f)
            {
                return;
            }
            
            if(CheckSight())
            {
                thresholdTime = (100.0f * Math::RandFloat()) * 0.02f + 5.0f;
                self.AnimState().Blend(anim_aiRunning, 4.0f, 8.0f, ANF_LOOP|ANF_ROOTMOTION);
				attackTime = Math::RandRange(4.0f, 6.0f);
            }
        }
    }
    
    /*
    ==============================================================
    OnDamage
    ==============================================================
    */
    
    void OnDamage(kActor @instigator, kDictMem @damageDef, const int damage)
    {
		//if not in challenge map 55 (bow)
		if (Game.GetCurrentMapID() != 55) {
			kActor @item = TossItem("Health_Small");		
			item.RunFxEvent("Item_Spawn");
		}
		
		if (damageDef is null) {
            return;
        }
		        
		bool bValue;
        if (damageDef.GetBool("bArrow", bValue) && bValue == true) {
			attackTime = 0.1f;
			kActor @arrow = TossItem("BP_Arrow");		
			arrow.Scale().Set(0.35f, 0.35f, 0.35f);
			arrow.Pitch() = Math::Deg2Rad(180);
			arrow.RunFxEvent("ArrowPickup_Glow");
        }
    }
	//------------------------------------------------------------------------------------------------------------------------
	kActor@ TossItem(const kStr &in itemName) {
		kActor @item = ActorFactory.Spawn(itemName,
                                          self.Origin().x,
                                          self.Origin().y,
                                          self.Origin().z + 32.0f,
                                          0, self.SectorIndex());
                                          
        item.Gravity() = 0.5f;
        item.BounceDamp() = 0.5f;
        item.ClipFlags() = (CF_DROPOFF|CF_CLIPEDGES|CF_NOCLIPACTORS|CF_COLLIDEFLOORS|CF_COLLIDEHEIGHT);
        item.Velocity().x = Math::RandCFloat() * 4.096f;
        item.Velocity().y = Math::RandCFloat() * 4.096f;
        item.Velocity().z = 4.096f + (Math::RandFloat() * 4.096f);
        
		return item;
	}
    /*
    ==============================================================
    OnDeath
    ==============================================================
    */
    
    void OnDeath(kActor @killer, kDictMem @damageDef)
    {
        kVec3 org = self.Origin();
        org.z += 51.2f;
        
        self.PlaySound("sounds/shaders/generic_3_energy_pickup.ksnd");
        Game.SpawnFx("fx/generic_260.kfx", org, self.SectorIndex());
        
        self.MarkPersistentBit(false);
        self.Remove();
		
		// if (damageDef is null) {
            // return;
        // }
		// bool bValue;
		// if (damageDef.GetBool("bArrow", bValue) && bValue == true) {
			// kActor @arrow = TossItem("BP_Arrow");
			// arrow.Scale().Set(0.35f, 0.35f, 0.35f);
			// arrow.Pitch() = Math::Deg2Rad(180);
			// arrow.RunFxEvent("ArrowPickup_Glow");
        // }
    }
    
    /*
    ==============================================================
    OnSpawn
    ==============================================================
    */
    
    void OnSpawn(void)
    {
        if((Math::RandByte() & 0x3) != 0)
        {
            turnOffset = 0.7854f;
        }
    }
    
    /*
    ==============================================================
    OnRestore
    ==============================================================
    */
    
    void OnRestore(void)
    {
        self.Remove();
    }
};

/*
==============================================================
TurokFish
==============================================================
*/

class TurokFish : ScriptObject
{
    kActor @self;
    kVec3 spawnOrigin;
    float thresholdTime;
    
    TurokFish(kActor @actor)
    {
        @self = actor;
        thresholdTime = 0.0f;
    }
    
    ~TurokFish()
    {
    }
    
    /*
    ==============================================================
    CheckSight
    ==============================================================
    */
    
    bool CheckSight(void)
    {     
        float fov = self.GetTurnYaw(Player.Actor().Origin());      
        return (Math::Fabs(fov) <= 45.0f && self.CanSee(Player.Actor()));
    }
    
    /*
    ==============================================================
    OnTick
    ==============================================================
    */
    
    void OnTick(void)
    {
        if(thresholdTime > 0.0f)
        {
            thresholdTime -= GAME_DELTA_TIME;
            
            kAngle an = Player.Actor().Yaw() + Math::pi;
            
            float x = self.Origin().x + (Math::Sin(an) * 614.4f);
            float y = self.Origin().y + (Math::Cos(an) * 614.4f);
            
            an = self.Yaw() + self.GetTurnYaw(kVec3(x, y, self.Origin().z));
            self.Yaw() = (an - self.Yaw()) * 0.035f + self.Yaw();
            
            if(thresholdTime <= 0.0f)
            {
                self.AnimState().Blend(anim_aiSwim1, Math::RandRange(2.0f, 8.0f), 10.0f, ANF_LOOP|ANF_ROOTMOTION);
            }
        }
        else
        {
            kAngle newYaw = self.GetAvoidanceAngle(spawnOrigin, 4.0f);
            
            self.Yaw() = (newYaw - self.Yaw()) * 0.01f + self.Yaw();
            
            if((self.AnimState().flags & ANF_BLEND) != 0)
            {
                return;
            }
            
            if((PlayLoop.Ticks() & 0x1FF) != 0)
            {
                return;
            }
            
            if(self.Origin().DistanceSq(Player.Actor().Origin()) >= 262144.0f)
            {
                return;
            }
                
            if(CheckSight())
            {
                thresholdTime = (100.0f * Math::RandFloat()) * 0.02f + 5.0f;
                self.AnimState().Blend(anim_aiSwim6, 6.0f, 10.0f, ANF_LOOP|ANF_ROOTMOTION);
            }
        }
    }
    
    /*
    ==============================================================
    OnBeginLevel
    ==============================================================
    */
    
    void OnBeginLevel(void)
    {
        float fh = self.FloorHeight();
        
        self.AnimState().Set(anim_aiSwim1, Math::RandRange(2.0f, 8.0f), ANF_LOOP|ANF_ROOTMOTION);
        spawnOrigin = self.Origin();
        
        self.Origin().z = (self.GetWaterHeight() - fh) * Math::RandRange(0.2f, 0.8f) + fh;
    }
    
    /*
    ==============================================================
    OnSpawn
    ==============================================================
    */
    
    void OnSpawn(void)
    {
    }
};

class TurokFish2 : ScriptObject
{
    kActor @self;
    kVec3 spawnOrigin;
    float thresholdTime;
	bool started = false;
    
	//------------------------------------------------------------------------------------------------------------------------
    TurokFish2(kActor @actor) {
        @self = actor;
        thresholdTime = 0.0f;
        spawnOrigin = self.Origin();
		self.Yaw() = Math::Deg2Rad(Math::RandRange(0.0f, 360.0f));
    }
	//------------------------------------------------------------------------------------------------------------------------
    bool CheckSight(void) {     
        float fov = self.GetTurnYaw(Player.Actor().Origin());      
        return (Math::Fabs(fov) <= 45.0f && self.CanSee(Player.Actor()));
    }
	//------------------------------------------------------------------------------------------------------------------------
    void OnTick(void) {
		if (Debug::IsActorsDisabled()) {
			self.AnimState().Stop();
			return;
		}
			
		if (!started) {
			started = true;
			self.AnimState().Set(anim_aiSwim1, Math::RandRange(2.0f, 8.0f), ANF_LOOP|ANF_ROOTMOTION);
		}
		
        if (thresholdTime > 0.0f) {
            thresholdTime -= GAME_DELTA_TIME;
            
            kAngle an = Player.Actor().Yaw() + Math::pi;
            
            float x = self.Origin().x + (Math::Sin(an) * 614.4f);
            float y = self.Origin().y + (Math::Cos(an) * 614.4f);
            
            an = self.Yaw() + self.GetTurnYaw(kVec3(x, y, self.Origin().z));
            self.Yaw() = (an - self.Yaw()) * 0.035f + self.Yaw();
            
            if(thresholdTime <= 0.0f)
            {
                self.AnimState().Blend(anim_aiSwim1, Math::RandRange(2.0f, 8.0f), 10.0f, ANF_LOOP|ANF_ROOTMOTION);
            }
        } else {
            kAngle newYaw = self.GetAvoidanceAngle(spawnOrigin, 4.0f);
            
            self.Yaw() = (newYaw - self.Yaw()) * 0.01f + self.Yaw();
            
            if((self.AnimState().flags & ANF_BLEND) != 0)
            {
                return;
            }
            
            if((PlayLoop.Ticks() & 0x1FF) != 0)
            {
                return;
            }
            
            if(self.Origin().DistanceSq(Player.Actor().Origin()) >= 262144.0f)
            {
                return;
            }
                
            if(CheckSight())
            {
                thresholdTime = (100.0f * Math::RandFloat()) * 0.02f + 5.0f;
                self.AnimState().Blend(anim_aiSwim6, 6.0f, 10.0f, ANF_LOOP|ANF_ROOTMOTION);
            }
        }
    }
	//------------------------------------------------------------------------------------------------------------------------
    void OnSpawn(void) {
    }
	//------------------------------------------------------------------------------------------------------------------------
};
