#include "shaftencoder.h"

#include "base/timer.h"
#include "network.h"

#include <iostream.h>      // cout
#include <iomanip.h>       // setw, setfill

#include <TSystem.h>       // gSystem
#include <TGLabel.h>       // TGLabel->SetText

#include <pthread.h>
#include <sys/resource.h>  // PRIO_PROCESS

ClassImp(ShaftEncoder);

ShaftEncoder::ShaftEncoder(const BYTE_t nodeid, const char *name, MLog &out)
    : NodeDrv(nodeid, name, out), fPos(0), fVel(0), fAcc(0),
    fTurn(0), fLabel(NULL), fPosHasChanged(false)
{
}

void ShaftEncoder::HandleSDO(WORD_t idx, BYTE_t subidx, LWORD_t val, timeval_t *tv)
{
    switch (idx)
    {
    case 0x1000:
        lout << "- Model: ";
        switch (val&0xffff)
        {
        case 0x0196:
            lout << "Shaft Encoder  Type: ";
            switch ((val>>16)&0xff)
            {
            case 0x01:
                lout << "Singleturn" << endl;
                return;
            case 0x02:
                lout << "Multiturn" << endl;
                return;
            default:
                lout << "?" << endl;
                SetZombie();
                return;
            }
        default:
            lout << "???" << endl;
            SetZombie();
            return;
        }
    case 0x100b:
        // Do not display, this is used for CheckConnection
        // lout << "Node ID: " << dec << val << endl;
        return;

    case 0x100c:
        lout << "- Guardtime: " << dec << val << "ms" << endl;
        return;

    case 0x100d:
        lout << "- Lifetimefactor: " << dec << val << endl;
        return;

    case 0x100e:
        lout << "- CobId for guarding: 0x" << hex << val << endl;
        return;

    case 0x6000:
    case 0x6500:
        lout << "- Counting: " << (val&1 ?"anti-clockwise":"clockwise") << "  ";
        lout << "HwTest: " <<   (val&2   ?"on":"off") << "  ";
        lout << "Scaling: " <<  (val&4   ?"on":"off") << "  ";
        lout << "Modulo: " <<   (val&4096?"on":"off") << endl;
        return;

    case 0x6001:
        lout << "- Logical Ticks/Revolution: " << dec << val << endl;
        return;

    case 0x6004:
        lout << "- Position: " << dec << val << endl;
        fPos  = val;
        fTurn = 0;
        return;


    case 0x6501:
        lout << "- Phys. Ticks/Revolution: " << dec << val << endl;
        fTicks = val;
        return;

    case 0x6502:
        //if (val==0)
        //    val = 1;  // Single Turn = Multiturn with one turn
        lout << "- Number of Revolutions: " << dec << val << endl;
        fTurns = val; 
        return;


    }
    cout << hex << setfill('0');
    cout << "Sdo=" << idx  << "/" << (int)subidx << ": 0x" << setw(8) << val;
    cout << endl;
}

void ShaftEncoder::DisplayVal()
{
    if (IsZombieNode())
    {
        fLabel->SetText(new TGString(""));
        fUpdPos = ~fPos;
        return;
    }

    char text[21];

    if (fPos!=fUpdPos && fLabel)
    {
        sprintf(text, "%ld", fPos);
        fLabel->SetText(new TGString(text));
        fUpdPos = fPos;
    }
}

void ShaftEncoder::HandlePDOType0(BYTE_t *data, timeval_t *tv)
{
    //
    // Decode information, we have a 14bit only
    //
    LWORDS_t pos = data[0] | (data[1]<<8) | (data[2]<<16); // | (data[3]<<24);
    if (pos==fPos)
        return;

    fPos = pos;
    fTime.SetTimer(tv);
    fPosHasChanged = true;
}

void ShaftEncoder::HandlePDOType1(BYTE_t *data, timeval_t *tv)
{
    //
    // Decode information, we have a 14bit only
    //
    LWORDS_t pos  = data[0] | (data[1]<<8) | (data[2]<<16); // | (data[3]<<24);
    BYTE_t   flag = data[4];

    if (fPos==pos)
        return;

    fPos=pos;
    fTime.SetTimer(tv);
    fPosHasChanged=true;

    flag=flag;
}

//#include <fstream.h>
//ofstream fout("log/shaftencoder.log");

void ShaftEncoder::HandlePDOType2(BYTE_t *data, timeval_t *tv)
{
    //
    // Decode information, we have a 14bit only
    //
    LWORDS_t pos = data[0] | (data[1]<<8) | (data[2]<<16); // | (data[3]<<24);

    fVel = data[4] | (data[5]<<8);
    fAcc = data[6] | (data[7]<<8);

    const int dnlim = fTicks/10;
    const int uplim = fTurns*fTicks-dnlim;

    int turn = fTurn;

    if (fPos > uplim && pos < dnlim)
        turn++;

    if (fPos < dnlim && pos > uplim)
        turn--;

    if (fPos==pos && fTurn==fTurn)
        return;

    fPos  = pos;
    fTurn = turn;

    fTime.SetTimer(tv);
    fPosHasChanged=true;
}

double ShaftEncoder::GetTime()
{
    return fTime.Now();
}

double ShaftEncoder::GetMjd()
{
    return fTime.GetMjd();
}

void ShaftEncoder::Init()
{
    //-----------------------------------------------------------------------
    //                    Start Setup of the Shaft Encoder
    //-----------------------------------------------------------------------

    StopGuarding();

    //
    // Requesting and checking (FIXME) type of encoder
    //
    lout << "- " << GetNodeName() << ": Requesting Hardware Type (0x1000)." << endl;
    RequestSDO(0x1000);
    WaitForSdo(0x1000);
    if (IsZombieNode())
        return;

    //
    // Read physical ticks per revolution
    //
    lout << "- " << GetNodeName() << ": Requesting physical ticks/revolution (SDO 0x6501)." << endl;
    RequestSDO(0x6501);
    WaitForSdo(0x6501);

    //
    // Read number of possible ticks per revolution
    //
    lout << "- " << GetNodeName() << ": Requesting possible ticks/revolution (SDO 0x6502)." << endl;
    RequestSDO(0x6502);
    WaitForSdo(0x6502);

    //
    // Request Lifetimefactor for unknown reason to make guarding
    // working in SE/Az... (FIXME)
    //
    //    lout << "- " << GetNodeName() << ": Requesting Lifetimefactor (Workaround, FIXME!) (SDO 0x100d)." << endl;
    //    RequestSDO(0x100c);
    //    WaitForSdo(0x100c);
    //    RequestSDO(0x100d);
    //    WaitForSdo(0x100d);

    //
    // Set logic ticks/revolution = physical ticks/revolution => scale factor = 1
    //
    lout << "- " << GetNodeName() << ": Configuring log. tick/rev (0x6001)." << endl;
    SendSDO(0x6001, fTicks);
    WaitForSdo(0x6001);

    //
    // Set maximum number of ticks (ticks * turns)
    //
    lout << "- " << GetNodeName() << ": Configuring max number of ticks (0x6002)." << endl;
    SendSDO(0x6002, (LWORD_t)(fTicks*fTurns));
    WaitForSdo(0x6002);

    //
    // Delete preset Value
    //
    lout << "- " << GetNodeName() << ": Delete preset value (0x6003)." << endl;
    SendSDO(0x6003, (LWORD_t)0xffffffff);
    WaitForSdo(0x6003);

    //
    // Configure PDOs
    //
    lout << "- " << GetNodeName() << ": Configuring PDOs (0x1802)." << endl;
    SendSDO(0x1802, 1, (LWORD_t)0x281);
    WaitForSdo(0x1802, 1);

    //
    // Request Parameter
    //
    lout << "- " << GetNodeName() << ": Requesting SDO 0x6000." << endl;
    RequestSDO(0x6000);
    WaitForSdo(0x6000);

    ReqPos();

    lout << "- " << GetNodeName() << ": Start Node (NMT)." << endl;
    SendNMT(kNMT_START);

    /*
     cout << "---1---" << endl;
     MTimeout t(1000);
     while (!t.HasTimedOut())
      usleep(1);
     cout << "---2---" << endl;
     */

    //    StartGuarding(175, 2); // 175
    // StartGuarding(10*GetId(), 2); // 175
}

void ShaftEncoder::CheckConnection()
{
    // Request Node number
    RequestSDO(0x100b);
    WaitForSdo(0x100b);
}

void ShaftEncoder::ReqPos()
{
    //
    // Request Position
    //
    lout << "- " << GetNodeName() << ": Requesting Position." << endl;
    RequestSDO(0x6004);
    WaitForSdo(0x6004);
}

void ShaftEncoder::SetPreset(LWORD_t pre)
{
    lout << "- " << GetNodeName() << ": Setting Preset." << endl;

    SendSDO(0x6003, (LWORD_t)pre);
    if (!WaitForSdo(0x6003))
        return;

    fPos  = pre%16384;
    fTurn = pre/16384;
}

void ShaftEncoder::StopDevice()
{
    lout << "- " << GetNodeName() << ": Stop Node (NMT)." << endl;
    SendNMT(kNMT_STOP);
}

