//----------------------------------------------------------------------------
///
/// \file   writerPredefined.cpp
///
/// \brief  update "predefined" objects in arena app file
///
/// \date   20230903
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


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


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


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


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

#include <QMap>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QSharedPointer>
#include <QJsonDocument>
#include <QJsonDocument>
#include <QDebug>

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

#include "writerPredefined.h"
#include "peripheryHelper.h"
#include "board.h"
#include "app.h"
#include <malloc.h>


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


int CWriterPredefined::writeFiles( )
{
   
   updatePredefined();
   return(0);
}


bool CWriterPredefined::updatePredefined( )
{
   QFile file;
   QFile outFile;
   bool sta=true;
   QJsonDocument settdoc;
   QJsonObject jsonObject;
   QJsonParseError error;
   QString fileName=app().getMainFile();
   QByteArray array;
   QString outFileName=getBasePath() + QFileInfo(fileName).baseName()
                         + "_predefined" + ".json";
   
   file.setFileName( fileName );
   if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
   {
      qFatal("Could not open file :%s", qPrintable( fileName ));
   }
   
   outFile.setFileName( outFileName );
   if(!outFile.open(QIODevice::WriteOnly | QIODevice::Text))
   {
      qFatal("Could not open output file :%s", qPrintable( outFileName ));
   }
   
   array=file.readAll();
   settdoc=QJsonDocument::fromJson( array, &error);
   if(error.error != QJsonParseError::ParseError::NoError )
   {
      qDebug() << "Parse Error in file " << fileName << ": " ;
      qDebug() << error.errorString() << " at offset " << error.offset;
      if(error.offset>40)
      {
         QString line=array.mid(error.offset-40, 80);
         qDebug() << "Line: " << line;
      }
      return(false);
   }
   jsonObject = settdoc.object();
   file.close();
   
   QJsonArray jsonArray = jsonObject["periphery"].toArray();
   int i1=0;
   for (auto value: jsonArray)
   {
      QJsonObject object=value.toObject();
      QJsonObject predefinedObject=object["predefined"].toObject();
      predefinedObject.insert( board().getId(), getPredefined(object) );
      object.insert("predefined", predefinedObject);
      
      //jsonArray.insert(1, object);
      jsonArray.replace(i1, object);
      i1++;
   }
   jsonObject.insert("periphery", jsonArray);
   settdoc.setObject(jsonObject);
   
   outFile.write( settdoc.toJson() );
   outFile.close();
   
   return(sta);
}


QString CWriterPredefined::getPredefined(const QJsonObject& object) const
{
   for(const auto &ref: app().getConstReferenceList())
   {
      if(   ( ref.getPeripheryType() == object["type"].toString() )
         && ( ref.getName() == object["name"].toString() ) )
      {
         return( predefined( *ref.getPeripheryLink() ) );
      }
   }

   // When the reference list does not contain the periphery, its probably
   // disabled.
   return( "disabled" );
}


QString CWriterPredefined::predefined(const CPeriphery &periphery) const
{
   QString pref;
   pref+=periphery.getPeripheryName();
   cutFabricateMarker( pref );
   
   for(const auto &consumes: periphery.getConsumesListConst() )
   {
      pref+=" ";
      if( consumes.getPeripheryLink() )
      {
         pref += predefined(*consumes.getPeripheryLink());
         cutFabricateMarker( pref );
      }
      else
      {
         pref+="NULL-Comsumer";
      }
   }
   
   return(pref);
}

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