/*
    main.cpp


    -------------------------------
    Copyright (c) 2020-2023 MCL Software
    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.
*/
#ifdef _WIN32
#include <irrlicht.h>
#else
#include <irrlicht/irrlicht.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>

#include "TitleMenu.h"
#include "LevelSwitcher.h"
#include "Base.h"
#include "RayCastHandler.h"


LevelSwitcher levelSwitcher;
RayCastHandler rayCastHandler;



int main(int argc, char *argv[])
{
    irr::u32 then;
    if(argc == 3 && std::string(argv[1]) == "--level" && atoi(argv[2]) >= 1 && atoi(argv[2]) <= 25)
    {
        levelSwitcher.currentLevel = atoi(argv[2]);
    }

    else if(argc > 1)
    {
        printf("\nUsage: --level <LEVEL NUMBER, 1...25>\nTry again and have a good day.\n=====================================\n");
        return 0;
    }

    else
    {
        levelSwitcher.currentLevel = 1;
        //scanf("%i", &levelSwitcher.currentLevel);
    }

    irr::core::vector2df movementVec;
    float angularVel;
    float rotVel;

    pb.device = createDevice(irr::video::EDT_OPENGL, irr::core::dimension2d<irr::u32>(pb.screenWidth, pb.screenHeight), 16, false, true, false, &pb.er);
    pb.driver = pb.device -> getVideoDriver();
    pb.scnmgr = pb.device -> getSceneManager();
    pb.guiEnv = pb.device -> getGUIEnvironment();
    irr::core::stringw motd[26] = {"PogoBijoux | ", "", "100 likes = part 2", "I bet you'll never guess what's under my dress...", "fuck you to home chris", "Xtreem!", "Most of y'all parents are dumb", "# Stand with MCL", "Think of the children!", "the ocelots and wolves will have there revenge", "it's not a mistake * it's a masterpiece *", "heroine i thot he was removed from the game", "queen of eggland dies :(", "i am 8 years old", "The latest and greatest", "L'beg to differ!", "The more you play with me, the happier L will be!", "Your shit's all retarded", "100 years of computer disease", "Keep projecting", "stfu stupid camper kid", "gr8 b8 m8 i r8 8/8", "Be sure to check out /r/LiminalSpace!", "Everything is the coolest here!", "L + ratio + rip bozo + go touch some grass", "Rate us on Itch.io!!!"};

    // Frame title //
    srand((unsigned int)time(0));
    motd[0] += motd[1 + rand() % 26];

    const wchar_t* currentMotd = motd[0].c_str();

    pb.device -> setWindowCaption(currentMotd);

    // Initialize audio engine //
    initAudioEngine();

      ////////////
     // Player //
    ////////////

    // Ambient light
    pb.scnmgr -> setAmbientLight(irr::video::SColorf(.3F, .3F, .36F, 1.0F));

    pb.player = pb.scnmgr -> addCubeSceneNode(90);

    pb.camera = pb.scnmgr -> addCameraSceneNode(pb.player, irr::core::vector3df(0, 0, 0), pb.player -> getAbsolutePosition(), true);
    pb.camera -> setPosition(irr::core::vector3df(-20, 30, 0));
    pb.camera -> setFarValue(100000.0F);


    // Main menu //
    if(!showTitleScreen())
    {
        return 0;
    }

    // Set shadow color //
    pb.scnmgr -> setShadowColor(irr::video::SColor(150, 0, 0, 0));

    // Store textures in 32-bits; this is needed for parallax mapping //
    pb.driver -> setTextureCreationFlag(irr::video::ETCF_ALWAYS_32_BIT, true);

    loadLevel(levelSwitcher.currentLevel);

    pb.device -> getCursorControl() -> setPosition(pb.screenWidth / 2, pb.screenHeight / 2);

    pb.device -> getCursorControl() -> setVisible(false); // Hide the cursor.

    while(pb.device -> run())
	{
	    pb.driver -> beginScene(true, true, irr::video::SColor(255, 113, 113, 133));

		// Get frame delta //
		const irr::u32 now = pb.device -> getTimer() -> getTime();
		const irr::f32 frameDeltaTime = (irr::f32)(now - then) / 1000.0F;
		then = now;



		if(pb.er.isKeyDown(irr::KEY_ESCAPE))
        {
            pb.device -> closeDevice();
        }

        //////////////
        // Movement //
        //////////////

        // Guide to degree angles

        // Every 90 degrees is 100 grads

        // 0   - 0 grads
        // 90  - 100 grads
        // 180 - 200 grads
        // 270 - 300 grads

        movementVec = irr::core::vector2df(0, 0);

        if(pb.er.isKeyDown(irr::KEY_KEY_W) || pb.er.isKeyDown(irr::KEY_KEY_S) || pb.er.isKeyDown(irr::KEY_KEY_D) || pb.er.isKeyDown(irr::KEY_KEY_A))
        {
            angularVel = pb.speed * frameDeltaTime;
        }

        if(pb.er.isKeyDown(irr::KEY_KEY_W))
        {
            movementVec.X -= angularVel;
        }

        if(pb.er.isKeyDown(irr::KEY_KEY_S))
        {
            movementVec.X += angularVel;
        }

        if(pb.er.isKeyDown(irr::KEY_KEY_A))
        {
            movementVec.Y += angularVel;
        }

        if(pb.er.isKeyDown(irr::KEY_KEY_D))
        {
            movementVec.Y -= angularVel;
        }



        if(pb.er.isKeyDown(irr::KEY_F2))
        {
            // Display position and rotation //
            pb.showPosition = true;
        }

        else if(pb.showPosition)
        {
            pb.showPosition = false;
        }

        // Commented out because it's not currently being used anywhere
        /*
        if(pb.er.isKeyDown(irr::KEY_F1))
        {
            // Get camera target //
            printf("\nCamTarget: %i\n", rayCastHandler.isPlayerLookingAtAABB(irr::core::aabbox3d<irr::f32>(irr::core::vector3df(-210, 0, -420), irr::core::vector3df(-205, 400, -415))));
        }*/

          /////////////////////
         // Camera rotation //
        /////////////////////

        // Up / Down //
        if(pb.er.isKeyDown(irr::KEY_UP) && pb.verticalCamRot < 100)
        {
            if(pb.verticalCamRot < -10)
                pb.verticalCamRot -= (6 * pb.verticalCamRot / 10) * frameDeltaTime;

            else
                pb.verticalCamRot += 56 * frameDeltaTime;
        }

        else if(pb.er.isKeyDown(irr::KEY_DOWN) && pb.verticalCamRot > -120)
        {
            if(pb.verticalCamRot < -10)
                pb.verticalCamRot += (6 * pb.verticalCamRot / 10) * frameDeltaTime;

            else
                pb.verticalCamRot -= 56 * frameDeltaTime;
        }

        irr::core::position2d<irr::s32> mousePos = pb.device -> getCursorControl() -> getPosition();

        pb.device -> getCursorControl() -> setPosition(pb.screenWidth / 2, pb.screenHeight / 2);

        irr::core::position2d<irr::s32> mouseMovement = pb.device -> getCursorControl() -> getPosition() - mousePos;

        rotVel = mouseMovement.X * pb.mouseSensitivity;
        rotVel *= -1;

        // Left / Right //
        if(pb.er.isKeyDown(irr::KEY_LEFT))
            rotVel = -300 * frameDeltaTime;

        else if(pb.er.isKeyDown(irr::KEY_RIGHT))
            rotVel = 300 * frameDeltaTime;

        else if(mouseMovement.X == 0)
            rotVel = 0;

        pb.verticalCamRot += mouseMovement.Y * pb.mouseSensitivity / 2;

        irr::core::vector3df playerRot = pb.player -> getRotation();
        irr::core::vector3df playerPos = pb.player -> getPosition();


        pb.player -> setRotation(irr::core::vector3df(-playerRot.X, playerRot.Y + rotVel, playerRot.Z));


        if(pb.er.isKeyDown(irr::KEY_KEY_W) || pb.er.isKeyDown(irr::KEY_KEY_S) || pb.er.isKeyDown(irr::KEY_KEY_D) || pb.er.isKeyDown(irr::KEY_KEY_A))
        {
            // rotating movementVec vector by playerRot.Y degrees
            movementVec.X = movementVec.X * cos(irr::core::degToRad(playerRot.Y)) - movementVec.Y * sin(irr::core::degToRad(playerRot.Y));
            movementVec.Y = movementVec.X * sin(irr::core::degToRad(playerRot.Y)) + movementVec.Y * cos(irr::core::degToRad(playerRot.Y));


            //pb.player -> setPosition(irr::core::vector3df(playerPos.X - cos(irr::core::degToRad(playerRot.Y + movementAngle)) * angularVel, playerPos.Y, playerPos.Z + sin(irr::core::degToRad(playerRot.Y + movementAngle)) * angularVel));
            pb.camera -> setTarget(irr::core::vector3df(playerPos.X - cos(irr::core::degToRad(playerRot.Y)) * angularVel, playerPos.Y + pb.verticalCamRot, playerPos.Z + sin(irr::core::degToRad(playerRot.Y)) * angularVel));

            pb.player -> setPosition(irr::core::vector3df(playerPos.X - movementVec.X * angularVel, playerPos.Y, playerPos.Z + movementVec.Y * angularVel));

            pb.player -> updateAbsolutePosition();
        }

        //pb.camera -> setTarget(irr::core::vector3df(playerPos.X - movementVec.X * angularVel, playerPos.Y + pb.verticalCamRot, playerPos.Z + movementVec.Y * angularVel));

        // Water on Level 7 //
        if(levelSwitcher.currentLevel == 7)
        {
            if(pb.player -> getAbsolutePosition().Y < -80)
            {
                waterSurface -> setRotation(irr::core::vector3df(0, 0, 180));
                pb.showWaterOverlay = true;
            }

            else
            {
                waterSurface -> setRotation(irr::core::vector3df(0, 0, 0));
                pb.showWaterOverlay = false;
            }
        }

        if(levelSwitcher.currentLevel == 14)
        {
            pb.showWaterOverlay = true;
        }

        else if(levelSwitcher.currentLevel != 7)
        {
            pb.showWaterOverlay = false;
        }


        // Temporary fix for levels 17 and 19//
        if(levelSwitcher.currentLevel == 19 && pb.player -> getAbsolutePosition().Y < 0)
        {
            pb.player -> setPosition(irr::core::vector3df(1000, 140, 1500));
        }

        else if(levelSwitcher.currentLevel == 17 && pb.player -> getAbsolutePosition().Y < 0)
        {
            pb.player -> setPosition(irr::core::vector3df(0, 1100, 1200));
        }

        levelSwitcher.checkIfPlayerShouldGoToNextLevel();
		pb.scnmgr -> drawAll();
		pb.drawIngameHUD();
		pb.guiEnv -> drawAll();
		pb.driver -> endScene();
        pb.guiEnv -> clear();
        levelSwitcher.proceedWithLevelSwitch();
    }

    stopAudioEngine();
    pb.device -> drop();
	return 0;
}
