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


FILE *create_data_file(char *name){
  char file_name[MAX_NAME];
  FILE *result = NULL;
  

  memset(file_name, 0, MAX_NAME);
  sprintf(file_name, "databases/%s.sto", name);
  result = fopen(file_name, "w");
  return result;
}

void add_data(relation_info *rel_info, FILE *data_out){
  int i = 0, len = 0, j = 0, len2 = 0;
  attr_info a_info;
  int int_val = 0;
  double double_val=0.0;
  //char_type char_val;
  char tmp_str[MAX_NAME];
  int char_len=0; 
  float num = 0.0;
  
  len = rel_info->rel_card;
  len2 = rel_info->num_attrs;
  
  for (i=0; i < len; ++i){
    printf("Reading tuple number: %d.\n", (i + 1));
    for (j=0; j < len2; ++j){
      a_info = rel_info->attributes[j];
      printf("Enter attribute %s: ", a_info.attr_name);
      switch(a_info.attr_type){
      case INT_TYPE:
	scanf("%d", &int_val);
	if (fwrite((void *) &int_val, 1, 4, data_out) != 4){
	  printf("Cannot write integer value to the file.\n");
	  exit(1);
	}
	break;
      case DOUBLE_TYPE:
	scanf("%f", &num);
	double_val = (double) num;
	if (fwrite((void *) &double_val, 1, sizeof(double), data_out) != 
	    sizeof(double)){
	  printf("Cannot write double value to the file.\n");
	  exit(1);
	}
	break;
      case CHAR_TYPE:
	char_len = a_info.type_size;
	memset(tmp_str, 0, char_len);
	scanf("%s", tmp_str);
	if (fwrite((void *) tmp_str, 1, char_len, data_out) != char_len){
	  printf("Cannot write char value to the file.\n");
	  exit(1);
	}	
	break;
      default:
	printf("Unknown attribute type code: %d.\n", a_info.attr_type);
	exit(1);
      }
    }
  }
}

int main(){
  char rel_name[MAX_NAME], f_name[MAX_NAME];
  relation_info *rel_info;
  int status;
  FILE *data_out = 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);
  }
  else if (status == ILLEGAL_FILE_FORMAT){
    printf("File %s has an illegal format.\n", f_name);
  }
  else if (status == NO_MEMORY){
    printf("Program ran out of memory.\n");
  }

  data_out = create_data_file(rel_name);
  
  if (data_out != NULL){
    printf("Enter the data for relation %s\n", rel_name);
    add_data(rel_info, data_out);
    fclose(data_out);
    printf("Done\n");
    exit(0);
  }
  else {
    printf("File could not be created.\n");
    exit(1);
  }
}

