//-----------------------------------------------------------------------------
///
/// \brief  Generic spi flash
///
///         Using Microchip SST25VF016B
///
/// \date   20160717
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


//---Includes------------------------------------------------------------------


//---General--------------------------


//---Own------------------------------

#include <biwak/spi_slave.h>
#include <biwak/flash_file.hpp>
#include <biwak/biwak.h>
#include <lepto/log.h>
#include <string.h>           // memcpy
#include <arpa/inet.h>        // htons


//---Defines-------------------------------------------------------------------


//---Implementation------------------------------------------------------------


/*    Manufacturer: 0xBF   SST
 *                               0x49     SST25VF010A 1MBit, Byte-AAI-program-only
 *                               0x41     SST25VF016B 16MBit, Word-AAI-program-only
 */

/// \brief  Le contructeur
///
CFlashFile::CFlashFile(const QString& fileName, bool needsToExist)
            :CFlash( 0, 0 )
            ,m_file(fileName)
{
   if( needsToExist && ( ! m_file.exists(  ) ) )
   {
      qFatal("Could not open flash file '%s'", qPrintable(fileName) );
   }
   if( ! m_file.open( QIODevice::ReadWrite ) )
   {
      qFatal("Could not open/create flash file '%s'", qPrintable( fileName ) );
   }
   m_erasePageSize=1;
   //setSize( 0x500 );
   setSize( m_file.size() );

    return;
}

CFlashFile::CFlashFile( const char *fileName, bool needsToExist )
    :CFlashFile( QString(fileName), needsToExist)
{
}

CFlashFile::CFlashFile( const QString& fileName, int size )
    :CFlashFile( fileName, false)
{
   setSize(size);
}

CFlashFile::~CFlashFile()
{
   return;
}

int CFlashFile::erasePage(address_t addr, int count /*=1*/ )
{
   return(0);
}

int CFlashFile::eraseAll()
{
   int ret=0;
   int value=0;
   m_file.seek(0);
   for(int i1=0; i1 < m_file.size(); i1++)
   {
      m_file.write( (char *)&value, 1);
   }
   return(ret);
}


int CFlashFile::readData(address_t addr, void *data, int size)
{
   int readSize;
   m_file.seek(addr);
   readSize=m_file.read( (char *)data, size);
   return( readSize != size ? -1 : 0 );
}


int CFlashFile::writeData(address_t addr, const void *data, int size)
{
   int ret=0;
   m_file.seek(addr);
   m_file.write( (char *)data, size);
   return(ret);
}


void CFlashFile::close()
{
   m_file.close();
}


//---fin-----------------------------------------------------------------------
