#include "enemy.h"
#include <iostream>

using namespace std;

Enemy::Enemy(Window &window, int x, int y)
{
    this->x = x;
    this->y = y;
    //populate rect with enemy image
    rect = new Rect("enemy.png", window, 1, 11);
    vector<pair<int, int> > enemy_animations;
    //set up animations
    for(int i = 0; i < 1; i++)
    {
        for(int j = 0; j < 11; j++)
        {
            enemy_animations.push_back(make_pair(i, j));
        }
    }
    rect->SetAnimationFrames(enemy_animations);
    //move to initial position
    rect->Move(x, y);
    //do the same with flipped rect
    flipped_rect = new Rect("enemy_flipped.png", window, 1, 11);
    vector<pair<int, int> > flipped_enemy_animations;
    for(int i = 0; i < 1; i++)
    {
        for(int j = 10; j >= 0; j--)
        {
            flipped_enemy_animations.push_back(make_pair(i, j));
        }
    }
    flipped_rect->SetAnimationFrames(enemy_animations);
    flipped_rect->Move(x, y);
    //initially, y velocity is 0
    vy = 0;
    //initially pointing to right
    right = true;
}

Enemy::~Enemy()
{
    delete rect;
}

void Enemy::Update(vector<Entity*> entities)
{
    //gravity
    vy += 10;
    if(right)
    {
        //move to right
        rect->Move(rect->get_x() + 10, rect->get_y() + vy);
        flipped_rect->Move(rect->get_x() + 10, rect->get_y() + vy);
    }
    else
    {
        //move to left
        rect->Move(rect->get_x() - 10, rect->get_y() + vy);
        flipped_rect->Move(rect->get_x() - 10, rect->get_y() + vy);
    }
    //too far to right
    if(rect->get_x() >= this->x + 100)
        right = false;
    //too far to left
    else if(rect->get_x() <= this->x - 100)
        right = true;
    for(int i = 0; i < entities.size(); i++)
    {
        //colliding with entity? -> stop moving down
        if(rect->CheckCollision(*(entities[i]->get_rect())))
            vy = 0;
        //correct position after collision
        rect->CorrectPosition(entities[i]->get_rect());
        flipped_rect->CorrectPosition(entities[i]->get_rect());
    }
}

void Enemy::Draw(SDL_Rect &camera, Window &window)
{
    //draw rect or flipped rect depending on direction
    if(right)
        rect->Draw(camera, window);
    else
        flipped_rect->Draw(camera, window);
}

Rect *Enemy::get_rect()
{
    return rect;
}