/*******************************************************************
 *                  Light Weight Chord Library 1.0                 *
 *  CopyRight(C) Yoshihide Matsumoto IDEON WorkingGroup 2003,2004  *
 *      matsumoto333@yahoo.co.jp (http://www.matchan.mydns.jp)     *
 *                                                                 *
 * Implementation of chord (Distributed Hash Table)                *
 * This program is distributed under GPL                           *
 * Light Weight Chord Library comes with ABSOLUTELY NO WARRANTY.   *
 * This is free software, and you are welcome to redistribute it   *
 * under certain conditions; read `COPYING' for details.           *
 *******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "file.h"
#include "id_list.h"
#include "misc.h"


//ファイルからIDリストを読み込む
void ReadFile(char *fname, IDLIST **IDList, char *pCacheDir){

  FILE *fp;
  FILE *fp2;
  char buf[32];
  char file_name[50];
  int  len;
  char *ret;
  struct stat st;


  sprintf(file_name,"./%s",pCacheDir);
  if(stat(file_name, &st) != 0){
    fprintf(stderr, "make dir %s\n", file_name);
    //make dir
    mkdir(file_name,0755);
  }else{
    if(!S_ISDIR(st.st_mode)){
      //error file exit
      fprintf(stderr, "File exsists. Plese delete %s\n", fname);
      return;
    }
  }


  sprintf(file_name,"./%s/%s", pCacheDir, fname);
  fp = fopen(file_name,"r");

  if(fp == NULL){   
    fprintf(stderr, "make file %s\n", file_name);

    //make idlist file
    fp = fopen(file_name,"w");
    fclose(fp);
    return;
  }
  
  while(fgets(buf,30,fp) != NULL){
    sprintf(file_name, "./%s/%d", pCacheDir, atoll(buf));
    if((fp2 = fopen(file_name, "r")) != NULL){
      id_insert(IDList, atoi(buf));
      fclose(fp2);
    }
    
  }
  
  fclose(fp);
  return;
}

void WriteFile(char *fname, IDLIST **IDList, char *pCacheDir){

  FILE *fp;
  char buf[32];
  char file_name[50];
  int  len;
  char *ret;
  IDLIST *idlist;
  idlist = *IDList;
  
  
  sprintf(file_name,"./%s/%s",pCacheDir,fname);
  fp = fopen(file_name,"w");

  if(fp == NULL){
    fprintf(stderr, "Error:Cannnot Open IDLIST file (w)\n");
      return;
  }

  while(idlist != NULL){
    fprintf(fp,"%d\n",idlist->id);    
    idlist = idlist->next;
  }

  fclose(fp);

  return;

}

void Data2File(int mcid, char *data, int size, char *pCacheDir){

  FILE *fp;
  char file_name[50];
  int  len;
  char *ret;

  sprintf(file_name,"./%s/%d",pCacheDir, mcid);
  fp = fopen(file_name,"w");

  if(fp == NULL){
    fprintf(stderr, "Error:Cannnot Open IDLIST file (w)\n");
      return;
  }

  fwrite(data, 1, size, fp);
  
  fclose(fp);
  return;

}
