#include "lister.h"

namespace cryptrav
{


Lister::Lister(ContextGlob* pContext, StateGlob* pState)
{
 contextP = pContext;
 stateP = pState;
}


CryptInfoList  Lister::entryCryptInfoList(QString pathInNominis, int sortType)
{
 CryptInfoList cryptInfoList;

 cryptInfoList.clear();


 Pather        pather(contextP);

 Translator    translator(contextP, stateP);


 QFileInfoList entryInfoList = QDir( pather.getNominisAbs(pathInNominis) ).entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::SortFlags(sortType));


 for (int i = 0; i < entryInfoList.length(); i++)
  {
   QFileInfo nomenInfo = entryInfoList.at(i);


   CryptInfo cryptInfo;

   cryptInfo.name = nomenInfo.fileName();


   if ( nomenInfo.isFile() )
    {
     cryptInfo.thisIsFile = true;


     OMEN::NomenData nomenData;
     OMEN::clearNomenData(&nomenData);

     if (OMEN::readNomen(nomenInfo.absoluteFilePath(), &nomenData) == CTERR_OK)
      {
       QString cryptomenStr = translator.makeCryptomenStr(nomenData.randomen);

       OMEN::CryptomenData cryptomenData;
       OMEN::clearCryptomenData(&cryptomenData);

       if (OMEN::readCryptomen(pather.getHarbourAbs("/." + cryptomenStr), &cryptomenData) == CTERR_OK)
        {

         if (cryptomenData.isNear) {
           cryptInfo.thisIsNear = true;

           translator.decryptTwoQwords( cryptomenData.nearSalt, &(cryptomenData.nearTime), &(cryptomenData.nearSize) );

           cryptInfo.nearTime = cryptomenData.nearTime;
           cryptInfo.thisNearSize = cryptomenData.nearSize;
          }

         if (cryptomenData.isFar) {
           cryptInfo.thisIsFar = true;

           translator.decryptTwoQwords( cryptomenData.farSalt, &(cryptomenData.farTime), &(cryptomenData.farSize) );

           cryptInfo.farTime = cryptomenData.farTime;
           cryptInfo.thisFarSize = cryptomenData.farSize;

          }

         cryptInfo.thisAction = cryptomenData.action;


         cryptInfoList << cryptInfo;
        }


       cryptomenStr.clear();

       OMEN::clearCryptomenData(&cryptomenData);
      }


     OMEN::clearNomenData(&nomenData);

    }
     else // it's a dir
    {
     cryptInfo.thisIsFile = false;
     cryptInfo.thisLastModified = nomenInfo.lastModified().toMSecsSinceEpoch();

     cryptInfoList << cryptInfo;
    }

  }


 return cryptInfoList;
}


Lister::~Lister()
{
 contextP = NULL;
 stateP = NULL;
}


} // namespace "cryptrav"
