#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <unistd.h>
#include <SDL_rotozoom.h>
#include <sys/soundcard.h>
#include <sys/statfs.h>
#include <sys/ioctl.h>
#include <dirent.h>
#include "fmtheaders.h"
#include "key.h"

int bytp_p_sec = 22050*2*2*2/2;

#define DEVICE_NAME "/dev/dsp"
#define MIXER_DEVICE_NAME "/dev/mixer"
#define BUF_SIZE 4096
int init_dsp(void)
{
  int audio_fd;
  if ((audio_fd = open(DEVICE_NAME, O_RDONLY, 0)) == -1) {
    /* Open of device failed */
    perror(DEVICE_NAME);
    return -1;
  }
  int format;
  format = AFMT_S16_LE;
  if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format) == -1) {
    /* fatal error */
    perror("SNDCTL_DSP_SETFMT");
    return -1;
  }
  if (format != AFMT_S16_LE) {
    /* 本设备不支持选择的采样格式. */
    printf("the format set error!\n");
    return -1;
  }
  int channels = 2; /* 1=mono, 2=stereo */
  if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
    /* Fatal error */
    perror("SNDCTL_DSP_CHANNELS");
    return -1;
  }
  if (channels != 2)
  {/* 本设备不支持立体声模式 ... */
    printf("the channels set error!\n");
    return -1;
  }
  int speed = 22050;
  if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &speed)==-1) {
    /* Fatal error */
    perror("SNDCTL_DSP_SPEED");
    return -1;
  }
  close(audio_fd);
  int mixer_fd;
  if ((mixer_fd= open(MIXER_DEVICE_NAME, O_WRONLY, 0)) == -1) {
    /* Open of device failed */
    perror(MIXER_DEVICE_NAME);
    return -1;
  }
  int vol = 0xffff;
  if(ioctl(mixer_fd,SOUND_MIXER_WRITE_MIC,&vol) == -1)
  {
    perror(MIXER_DEVICE_NAME);
    return -1;

  }
  close(mixer_fd);

  return 0;
}
long get_free_space(void)
{
  long i;
  struct statfs disk_statfs;
  printf("Get: %d\n", statfs("/mnt/memory", &disk_statfs));
  i = disk_statfs.f_bsize*disk_statfs.f_bsize;

  return i;
}
#define MAX_FREE_SPACE 300*1024*1024
long caclute_free_time_sec(void)
{
  long free_space_byte = get_free_space();
  if(free_space_byte >= MAX_FREE_SPACE)
    free_space_byte = MAX_FREE_SPACE;
  printf("free_space_byte is %ld\n",free_space_byte);
  int free_time = free_space_byte/bytp_p_sec;
  printf("free_time is %d\n",free_time);
  return free_time;
}
int start_record(char *filename)
{
  if(init_dsp() == -1)
    return -1;
  int audio_fd;
  unsigned char audio_buffer[BUF_SIZE];
  if ((audio_fd = open(DEVICE_NAME, O_RDONLY, 0)) == -1) {
    /* Open of device failed */
    perror(DEVICE_NAME);
    printf("open %s fail\n",DEVICE_NAME);
    return -1;
  }
  printf("open %s success\n",DEVICE_NAME);
  int len;
  FILE *fp_wave;
  printf("%s %d :filename is %s\n",__FILE__,__LINE__,filename);
  fp_wave = fopen(filename,"wb");
  if(!fp_wave)
    return -1;
  WaveHeader wh;
  int dsp_speed = 22050;
  int dsp_stereo = 1;
  unsigned long samplesize = 16;
  int cnt = 0;
  fwrite(&wh,sizeof(WaveHeader),1,fp_wave);

  wh.main_chunk = RIFF;
  wh.length= cnt+ sizeof(WaveHeader) - WAVE_RIFF_FLEN;
  wh.chunk_type = WAVE;
  wh.sub_chunk = FMT;
  wh.sc_len = 16;
  wh.format = PCM_CODE;
  wh.modus = dsp_stereo ? 2 :1;
  wh.sample_fq = dsp_speed;
  wh.byte_p_spl = ( (samplesize == 8) ? 1 : 2) * (dsp_stereo ? 2 :1);
  bytp_p_sec = wh.byte_p_sec = dsp_speed * wh.modus * wh.byte_p_spl/2;

  wh.bit_p_spl = samplesize;
  wh.data_chunk = DATA;
  wh.data_length = cnt;
  int buffer_len = 0;
  int run = 1;
  int free_time = caclute_free_time_sec();
  printf("%s %d free_time is %d\n",__FILE__,__LINE__,free_time);
  int cur_time = 0;
  while(run)
  {
#if 0
    while(SDL_PollEvent(&event))  
    {
      if(event.type == SDL_KEYDOWN)
      {
        key = event.key.keysym.sym;
        if(key == DINGOO_BUTTON_B)
        {
          is_recording = -1;
          run = 0;
          break;
        }
        if(key == DINGOO_BUTTON_A)
        {
          is_recording = 1;
          run = 0;
          break;
        }
      }

    }
#endif
    if ((len = read(audio_fd, audio_buffer, BUF_SIZE)) == -1) 
    {
      perror("audio read");
      run = 0;
    }
    buffer_len = fwrite(audio_buffer,len,1,fp_wave);

    cnt+=len;
    if(buffer_len != 1)
    {
      perror("write file error\n");
      run = 0;
    }
    cur_time = 1*cnt/bytp_p_sec;
    if(cur_time > 10)
      run = 0;
  }

  wh.length= cnt+ sizeof(WaveHeader) - WAVE_RIFF_FLEN;
  wh.data_length = cnt;
  fseek(fp_wave,SEEK_SET,0);
  fwrite(&wh,sizeof(WaveHeader),1,fp_wave);

  printf("record end\n");
  fflush(fp_wave);
  fsync(fileno(fp_wave));
  fclose(fp_wave);
  close(audio_fd);
  return 0;
}

