/*

--------
|SKRUZD|
--------

The MIT License

Copyright (c) 2006 Inko Illarramendi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/


#include <crystalspace.h>

#include <physicallayer/entity.h>
#include <physicallayer/propclas.h>
#include <propclass/linmove.h>
#include <propclass/prop.h>
#include <propclass/trigger.h>
#include <propclass/region.h>

#include <propclass/tooltip.h>
#include <propclass/timer.h>
#include <propclass/move.h>
#include <propclass/input.h>
#include <propclass/solid.h>
#include <propclass/colldet.h>

#include "behave.h"
#include "bweapon.h"

BehaviourWeapon::BehaviourWeapon (iCelEntity* entity, BehaviourLayer* bl, iCelPlLayer* pl)
        : BehaviourCommon (entity, bl, pl, app)
{
    id_pctimer_wakeup = pl->FetchStringID ("pctimer_wakeup");
    id_pctimer_wakeupframe = pl->FetchStringID ("pctimer_wakeupframe");
}

bool BehaviourWeapon::SendMessage (csStringID msg_id,
                                   iCelPropertyClass* pc,
                                   celData& ret, iCelParameterBlock* params, va_list arg)
{
    /// If weapon is active, it will check for enemies in radius and
    ///destroy them.
    /// If the timer wakes up, the weapon is ended.

    iCelEntity* weapon_entity;
    iCelEntity* entity;

    weapon_entity = pc-> GetEntity();
    csRef<iPcMesh> pcmesh = CEL_QUERY_PROPCLASS_ENT (
                                weapon_entity, iPcMesh);
    csRef<iPcTimer> pctimer = CEL_QUERY_PROPCLASS_ENT (
                                  weapon_entity, iPcTimer);

    if ((msg_id == id_pctimer_wakeupframe) && (pcmesh->IsVisible()))
    {  ///Here we will check the enemies hit by the weapon

        // Get the sector and position of the weapon and check the enemies.
        iSector* sector = pcmesh->GetMesh ()->GetMovable ()->GetSectors ()->Get (0);
        csVector3 pos = pcmesh->GetMesh ()->GetMovable ()->GetTransform ()
                        .This2Other (csVector3 (0, 0, 0));
        csRef<iCelEntityList> entitylist = pl->FindNearbyEntities (sector, pos, 0.5);
        size_t listcount=entitylist->GetCount();

        if (listcount>1)
        {
            //get the enemies
            const char* name;
            size_t i;
            uint ID;
            for (i=0;i<listcount;i++)
            {
                //we check all the enemies in radius and destroy them
                entity=entitylist-> Get(i);
                name=entity->GetName();
                ID= entity->GetID();
                if (!strcmp (name, "bad2"))
                {
                    // Create the explosion of destroying the enemy
                    csRef<iCelEntity> explosion_entity;
                    explosion_entity = pl->CreateEntity ("explosion",  bl, "shoot_behave",
                                                         "pcmesh",
                                                         "pclinearmovement",
                                                         "pctimer",///END THE SHOOT
                                                         0);
                    if (!explosion_entity)
                        printf("Error creating acid entity!");

                    // Get the iPcMesh interface
                    csRef<iPcMesh> pcmeshexpl = CEL_QUERY_PROPCLASS_ENT (
                                                    explosion_entity, iPcMesh);
                    pcmeshexpl->SetPath ("/this/model");
                    pcmeshexpl->SetMesh ("partExplosion", "explosion");
                    if (!pcmeshexpl->GetMesh ())
                        printf("Error loading model!");

                    // Get the position of the enemy to center the explosion
                    csRef<iPcMesh> mesh = CEL_QUERY_PROPCLASS_ENT (
                                              entity, iPcMesh);
                    pos = mesh->GetMesh ()->GetMovable ()->GetTransform ()
                          .This2Other (csVector3 (0, 0, 0));

                    // Get iPcLinearMovement of explosion to set the position
                    csRef<iPcLinearMovement> pclinmovexpl = CEL_QUERY_PROPCLASS_ENT (
                                                                explosion_entity, iPcLinearMovement);
                    pclinmovexpl -> SetFullPosition (pos, 0, sector);

                    // Set the timer to end the explosion
                    csRef<iPcTimer> pctimerexpl = CEL_QUERY_PROPCLASS_ENT (
                                                      explosion_entity, iPcTimer);
                    pctimerexpl-> WakeUp(5000, true);

                    // Move the enemy away from the map and hide it
                    pos = mesh->GetMesh ()->GetMovable ()->GetTransform ()
                          .This2Other (csVector3 (0, -100, 0)); //to send it under the map
                    mesh-> MoveMesh (sector, pos);
                    mesh -> Hide();

                    //Get the level and its properties to update the score
                    iCelEntity* level_entity = pl->FindEntity ("level");
                    csRef<iPcProperties> pcproperties = CEL_QUERY_PROPCLASS_ENT (
                                                            level_entity, iPcProperties);
                    long int score = pcproperties-> GetPropertyLong (pcproperties-> GetPropertyIndex ("score"));
                    score=score+1;
                    int scor = (int) score;
                    pcproperties -> SetProperty ("score", score);

                    // Get the iPcTooltip interface to print the score
                    csRef<iPcTooltip> pctooltip = CEL_QUERY_PROPCLASS_ENT (
                                                      level_entity, iPcTooltip);
                    char scorec[3];
                    sprintf(scorec,"KILLS %d", scor);
                    pctooltip->SetBackgroundColor (-1, -1, -1);
                    pctooltip->SetText(scorec);
                    pctooltip->Show(50,50);
                }//if
            }//for
        }//if
        return true;
    }//if wakeupframe


    if (msg_id == id_pctimer_wakeup)
    { ///The timer of weapon is ended, so we will hide it.

        //Get the iPcLinearMovement of weapon and position.
        csRef<iPcLinearMovement> pcweaponlinmov = CEL_QUERY_PROPCLASS_ENT (
                    weapon_entity, iPcLinearMovement);
        csVector3 pos;
        iSector* sector;
        float yrot;
        pcweaponlinmov-> GetLastFullPosition ( pos, yrot ,sector );
        // Move away the weapon entity
        pcweaponlinmov -> ExtrapolatePosition (100);

        //Set the movement of the player to original values.
        //Get the entity
        iCelEntity* player_entity = pl->FindEntity ("player");
        csRef<iPcMesh> player_pcmesh = CEL_QUERY_PROPCLASS_ENT (
                                           player_entity, iPcMesh);
        // Get the iPcActorMove property and set the speeds
        csRef<iPcActorMove> player_pcactormove = CEL_QUERY_PROPCLASS_ENT (
                    player_entity, iPcActorMove);
        player_pcactormove->SetMovementSpeed (3.0f);
        player_pcactormove->SetRunningSpeed (5.0f);
        player_pcactormove->SetRotationSpeed (1.75f);

        if (player_pcactormove-> IsMovingForward () )
            player_pcactormove -> Forward (true);
        else if (player_pcactormove-> IsMovingBackward ())
            player_pcactormove -> Backward (true);
        if (player_pcactormove-> IsRotatingLeft ())
            player_pcactormove -> RotateLeft (true);
        else if (player_pcactormove-> IsRotatingRight ())
            player_pcactormove -> RotateRight (true);

        return true;
    }
    return BehaviourCommon::SendMessage (msg_id, pc, ret, params, arg);

}
