//----------------------------------------------------------------------------
///
/// \file   writerSymbolMap.cpp
///
/// \brief  Generates symbol map file
///
/// \date   20201211
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


//---Documentation------------------------------------------------------------


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


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


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

#include <QMap>
#include <QFile>
#include <QTextStream>
#include <QSharedPointer>
#include <QProcess>
#include <QDebug>

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

#include "writerSymbolMap.h"
#include "board.h"
#include "app.h"

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


int CWriterSymbolMap::writeFiles()
{
   writeSymbolmapFile( );

   return(0);
}

void CWriterSymbolMap::writeSymbolmapFile()
{
   QMap <QString, int> typeCounter;
   QString line;
   QFile file( getBasePath() + "arena_generated.symmap" );
   if (!file.open(QFile::WriteOnly | QFile::Truncate))
      qFatal("Could not open header file for writing");
   QTextStream out(&file);

   out << "\n";

   // There has to be at least one file in the symfile to be valid anyways
   QStringList irqHandlers=pinmux().getIrqHandlers();

   irqHandlers+="SysTick_Handler";

   for( QString const &irqHandler: irqHandlers )
   {
      if(!irqHandler.isEmpty())
         out << QString("%1 = %1_imp;\n").arg(irqHandler);
   }

   for ( const QSharedPointer<CPeriphery> &periphery: board().listConst())
   {
      if(periphery->isUsed())
      {
         const CConstructor *constructor=m_constructorPool.getConstructor( CPeripheryConstPtr ( &(*periphery) ) );
         if(constructor)
         {
            //qWarning() << "SymbolMap: " << periphery->getPeripheryType() << ":" << constructor->getAttribute("symbolMap");
            for ( auto sym: constructor->getJsonObject()["symbolMap"].toArray() )
            {
               // qWarning() << sym.toObject().key() << " = " << sym.toObject().value();
               out << QString( sym.toString() ) << ";\n";
            }
         }
      }
   }

   for( auto from: app().SymbolMap.keys() )
   {
      out << QString("%1 = %2;\n").arg(from).arg(app().SymbolMap[from]);
   }

   for( auto from: app().symbolMapList )
   {
      if(from.contains("="))
      {
         out << QString("%1;\n").arg(from);
      }
      else
      {
         out << QString("%1 = exception;\n").arg(from);
      }
   }

   file.close();
}

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