#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "schema.h"
#include "error.h"
#include "tuple.h"
#include "iterator.h"
#include "scan_iterator.h"


proj_attr_list *make_projs(relation_info *rel_info){
  int i=0, len = 0;
  proj_attr_list *proj_list = NULL;
  
  len = rel_info->num_attrs;
  proj_list = (proj_attr_list *) calloc(1, sizeof(proj_attr_list));
  proj_list->num_projs = len;
  proj_list->projections = (proj_attr *) calloc(len, sizeof(proj_attr));
						    
  for (i=0; i < len; ++i){
    proj_list->projections[i].attr_pos = i;
    memcpy((void *) &(proj_list->projections[i].a_info),
	   (void *) &(rel_info->attributes[i]),
	   sizeof(attr_info));
  }
  return proj_list;
}

int main(){
  char rel_name[MAX_NAME], f_name[MAX_NAME];
  relation_info *rel_info;
  int status;
  proj_attr_list *proj_list;
  scan_iterator *s_iter;
  bool done = false;
  tuple *next_tuple = NULL;
  
  memset(rel_name, 0, MAX_NAME);
  memset(f_name, 0, MAX_NAME);
  
  printf("Enter the relation name: ");
  scanf("%s", rel_name);
  printf("Relation name entered: %s\n", rel_name);
  sprintf(f_name, "schemas/%s.sf", rel_name);
  printf("Accessing schema file: %s\n", f_name);

  rel_info =  get_relation_info(f_name, status);
  if (status == OK){
    print_relation_schema(rel_info);
  }
  else if (status == FILE_NOT_FOUND){
    printf("File %s was not found.\n", f_name);
    exit(1);
  }
  else if (status == ILLEGAL_FILE_FORMAT){
    printf("File %s has an illegal format.\n", f_name);
    exit(1);
  }
  else if (status == NO_MEMORY){
    printf("Program ran out of memory.\n");
    exit(1);
  }

  printf("Making the projection list.\n");
  proj_list = make_projs(rel_info);
  printf("Making the scan iterator.\n");
  s_iter = make_scan_iterator(rel_info,proj_list, NULL, NULL);
  printf("Opening the scan iterator.\n");
  if (open_scan_iterator(s_iter) != OK){
    printf("Cannot open the iterator.\n");
    exit(1);
  }

  //print_attr_names(rel_info);
  
  while(!done){
    next_tuple = next_scan_iterator(s_iter, status);
    if (status == OK){
      print_tuple(next_tuple, stdout);
    }
    else {
      done = true;
    }
  }
  printf("Closing the iterator.\n");
  if (close_scan_iterator(s_iter) != OK){
    printf("Cannot close the iterator.\n");
    exit(1);
  }

  exit(0);
  
}
