#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>
#include <stack>
#include <map>

#include "Tree.h"
#include "CMinusParser.hh"
#include "CodeGenerator.h"
#include "CodeEmitter.h"
#include "SymbolTable.h"

using std::string;
using std::ostringstream;
using std::map;
using std::stack;

//******

// File we will emit assembly instructions to
FILE* codeFilePtr;

// Input and output routine pointers
extern TreePtr inputFunc;
extern TreePtr outputFunc;

// Fixed activation record offsets
//   for bookkeeping information
// All offsets are relative to %ebp
//       (IA32 base/frame pointer)

// First argument frame offset
//   Where caller has placed first argument
const int FIRST_ARG_OFFSET = +8;

// Start of local variable area
const int LOCAL_VAR_OFFSET = -4;

void
generateCodeHelper (TreePtr tree, int offset, bool isAddress);

void
generateStatement (TreePtr tree, int offset);

void
generateExpression (TreePtr tree, int offset, bool isAddress);

void
generateDeclaration (TreePtr tree, int offset);

string
generateLabel ();

//******

// Primary code generator function
void
generateCode (TreePtr syntaxTree, const string& codeFilename)
{
  codeFilePtr = fopen (codeFilename.c_str (), "w");

  // Put code file name into code file as comment
  string comment ("File: " + codeFilename);

  emitSeparator (1);
  emitComment ("C-Minus Compilation to IA-32 Code");
  emitComment (comment);
  emitSeparator (1);

  generateCodeHelper (syntaxTree, 0, false);

  // Call functions to do code gen for standard procedures
  //   input and output

  // ...

  emitComment ("That's all Folks...");

  fclose (codeFilePtr);
}

// generateCodeHelper is invoked recursively by the
//   generate{Statement,Expression,Declaration} routines

// offset:    offset for last occupied stack slot

// isAddress: if true generating code for l-value
void
generateCodeHelper (TreePtr tree, int offset, bool isAddress)
{
  if (tree != nullptr)
  {
    switch (tree->nodeType)
    {
      case StmtNode:
        generateStatement (tree, offset);

        break;

	// Other cases

      default:
        emitComment ("Error: missing case in generateCodeHelper");

        break;
    }
  }
}

//******

void
generateStatement (TreePtr tree, int offset)
{
  if (tree != nullptr)
    switch (tree->stmt.stmtType)
    {
      case IfStmt:
      {
        emitComment ("-> if");
        TreePtr condition = tree->children[0];
        // Code gen for test expression
        generateCodeHelper (condition, offset, false);

        emitComment ("if: jump to else");
        string labelElse = generateLabel ();
        emitInstruction ("cmpl", "$0, %eax", "is condition false?");
        emitInstruction ("je", labelElse, "if: jmp to else");

        // Code gen for then
        TreePtr thenClause = tree->children[1];
        generateCodeHelper (thenClause, offset, false);

        emitComment ("if: jump to end");
        string labelEnd = generateLabel ();
        emitInstruction ("jmp", labelEnd, "if: jmp to end");

        // Code gen for else
        emitLabel (labelElse, "else label");
        TreePtr elseClause = tree->children[2];
        generateCodeHelper (elseClause, offset, false);

        emitLabel (labelEnd, "end label");

        emitComment ("<- if");
        break;
      }

      case CompoundStmt:
      {
        emitComment ("-> compound statement");

        TreePtr declarations = tree->children[0];
        TreePtr body = tree->children[1];
        // Process local vars
        int localSize = 0;
	// Walk list of declarations
	//   Determine localSize
	//   Allocate localSize space on stack
	//   Deal with arrays later!

	// Handle the body
}

//******

// Invariant: expression result will be stored in %eax
//   when function returns
void
generateExpression (TreePtr tree, int offset, bool isAddress)
{
  if (tree != nullptr)
    switch (tree->expr.exprType)
    {
      case ConstExpr:
      {
        emitComment ("-> constant");
	ostringstream os;
	os << '$' << tree->expr.attr.val << ", %eax";
	emitInstruction ("movl", os.str (), "load const");
        emitComment ("<- constant");

        break;
      }

      case IdExpr:
      {
        emitComment ("-> id");
	// ...

        break;
      }

      case OperatorExpr:
      {
        emitComment ("-> op");

        TreePtr arg1 = tree->children[0];
        TreePtr arg2 = tree->children[1];

        // Code gen for eax = right operand
        //   unless we're dealing with INCR or DECR
	//   in which case arg2 is null
        if (arg2 != nullptr)
        {
          generateCodeHelper (arg2, offset, false);

          // Code gen to push right operand
          emitInstruction ("pushl", "%eax", "op: push right");
        }

        // Code gen for eax = left arg
        if (tree->expr.attr.op == ASSIGN || tree->expr.attr.op == INCR
            || tree->expr.attr.op == DECR)
          generateCodeHelper (arg1, offset - 4, true);
        else
          generateCodeHelper (arg1, offset - 4, false);

        // If not an INCR or DECR
        if (arg2 != nullptr)
          // Pop right operand
          emitInstruction ("popl", "%ebx", "op: pop right");

        // Gen appropriate RO instruction
        switch (tree->expr.attr.op)
        {
	case INCR:

	  emitInstruction ("incl", "(%eax)", "++op");
	  emitInstruction ("movl", "(%eax), %eax", "load value");

	  break;

	  // Other cases

	default:

	  emitComment ("BAD: Unknown operator");

	  break;
	}

        emitComment ("<- op");

        break;
      }

      case CallExpr:
      {
	// ...

        emitComment ("<- call");

        break;
      }

      case SubscriptExpr:
      {
	// ...

        break;
      }

      default:
      {
        emitComment ("Error: missing expression case in generateExpression");

        break;
      }
    }
}

//******

void
generateDeclaration (TreePtr tree, int offset)
{
  if (tree != nullptr)
    switch (tree->decl.declType)
    {
      case VariableDecl:
      {
        emitSeparator (1);

        char comment[50];
        sprintf (comment, "-> allocating global var: %s", tree->decl.name);
        emitComment (comment);

        if (tree->decl.nestLevel != 0)
          emitComment ("BAD: allocating non-global at global level");

        int varSize;
        // Calculate how much space to allocate
        if (tree->decl.isArray)
          varSize = tree->decl.arraySize * 4;
        else
          varSize = 4;

	ostringstream os;
	os << tree->decl.name << ", " << varSize;
	// Allocate space in bss region
	emitInstruction (".comm", os.str (), "bss space for global");

        emitComment ("<- vardecl");

        // Recurse on subsequent global declarations
        generateCodeHelper (tree->sibling, offset, false);

        break;
      }

      case FunctionDecl:
      {

        break;
      }

      default:
      {
        emitComment ("Error: missing declaration case in generateDeclaration");

        break;
      }
    }
}

//******

string
generateLabel ()
{
  static int labelNumber = 0;
  ostringstream oss;
  oss << ".L" << labelNumber++;

  return oss.str ();
}

