#include "stdafx.h"

#include "PatternMovement.h"
#include "PnxUtility.h"
#include "DxWrapper.h"

const int PatternMovement::PATTERN_SIZE = 50;
const int PatternMovement::PATTERN_FRAME_DURATION_MIN = 1000;
const int PatternMovement::PATTERN_FRAME_DURATION_MAX = 3000;
const float PatternMovement::ROTATION_RANGE_MIN = 20.0f;        // Winkel in degree, um den die Flugrichtung pro patternshift mindestens geändert werden muss
const float PatternMovement::ROTATION_RANGE_MAX = 45.0f;        // Winkel in degree, um den die Flugrichtung pro patternshift maximal geändert werden darf

PatternMovement::PatternMovement(EnemyCraft* host)
{
    m_pHostObject = host;
    m_Pattern = new int[PATTERN_SIZE];
    InitializeRandomPattern();
    m_PatternIndex = -1;
    ShiftPatternIndex();

}

PatternMovement::~PatternMovement(void)
{
    delete [] m_pHostObject;
}


void PatternMovement::InitializeRandomPattern()
{
    int sign = 0;

    for (int i = 0; i < PATTERN_SIZE; i++ )
    {
        m_Pattern[i] = PnxUtility::GetRandomInt(static_cast<int>(ROTATION_RANGE_MIN), static_cast<int>(ROTATION_RANGE_MAX));

        sign = PnxUtility::GetRandomInt(0,1);
        if (sign)
        {
            m_Pattern[i] *= -1;
        }
    }
}

void PatternMovement::Cycle( float deltaMs )
{
    m_IndexSwitchCountdown -= static_cast<int>(deltaMs);
    if (m_IndexSwitchCountdown < 0)
        ShiftPatternIndex();

    if (m_targetRotZ > m_pHostObject->m_RotZ)
    {
        m_pHostObject->m_RotZ += m_pHostObject->m_RotationSpeed * deltaMs;
        if (m_targetRotZ < m_pHostObject->m_RotZ)
            m_pHostObject->m_RotZ = m_targetRotZ;
    }
    if (m_targetRotZ < m_pHostObject->m_RotZ)
    {
        m_pHostObject->m_RotZ -= m_pHostObject->m_RotationSpeed * deltaMs;
        if (m_targetRotZ > m_pHostObject->m_RotZ)
            m_pHostObject->m_RotZ = m_targetRotZ;
    }
}

void PatternMovement::Draw()
{
}

/** wird aufgerufen, sobald der Countdown abgelaufen ist, und der nächste Wert des Movement Patterns geladen werden soll
*/
void PatternMovement::ShiftPatternIndex()
{
    m_PatternIndex++;
    if (m_PatternIndex == PATTERN_SIZE)
        m_PatternIndex = 0;

    m_targetRotZ = m_pHostObject->m_RotZ + m_Pattern[m_PatternIndex];
    m_targetRotZ = static_cast<float>(static_cast<int>(m_targetRotZ) % 360);

    m_IndexSwitchCountdown = PnxUtility::GetRandomInt(PATTERN_FRAME_DURATION_MIN, PATTERN_FRAME_DURATION_MAX);


    /*
    //DxWrapper* dxw = DxWrapper::Instance();

    //dxw->DrawLine(targetVector + m_pHostObject->m_Position, m_pHostObject->m_Position);
   
    std::ostringstream s1(std::ostringstream::out);
    s1 << "ShiftPatternIndex() PatternIndex=" << m_PatternIndex << "    m_Pattern[m_PatternIndex]=" << m_Pattern[m_PatternIndex] << "   targetRotZ=" << m_targetRotZ << "    countdown=" << m_IndexSwitchCountdown << std::endl;    
    dxw->WriteLog(s1.str());
    */
}