//**************************************************************************
//*                     This file is part of the                           *
//*                      Mpxplay - audio player.                           *
//*                  The source code of Mpxplay is                         *
//*        (C) copyright 1998-2006 by PDSoft (Attila Padar)                *
//*                    http://mpxplay.cjb.net                              *
//*                  email: mpxplay@freemail.hu                            *
//**************************************************************************
//*  This program is distributed in the hope that it will be useful,       *
//*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *
//*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                  *
//*  Please contact with the author (with me) if you want to use           *
//*  or modify this source.                                                *
//**************************************************************************
//function:playlist save

#include "newfunc\newfunc.h"
#include "control\control.h"
#include "display\display.h"
#include "playlist.h"

extern char *m3usavename,*mxusavename,*cuesavename;

static char *savelist_get_relative_filename(char *filename,char *path,unsigned int pathlen)
{
 char csave,*rp;

 csave=filename[pathlen];
 filename[pathlen]=0;
 if(pds_stricmp(filename,path)==0){  // if path of startdir and save-dir is the same
  rp=&filename[pathlen+1];  // save relative to currdir (subdir\filename.mp3)
 }else{
  if(pds_getdrivenum_from_path(filename)>=0 && pds_getdrivenum_from_path(filename)==pds_getdrivenum_from_path(path)){ // drives are same
   rp=&filename[2];   // save relative to rootdir (\subdir\filename.mp3)
  }else{
   rp=filename;       // save with full path      (d:\subdir\filename.mp3)
  }
 }
 filename[pathlen]=csave;
 return rp;
}

static void save_m3u_playlist(struct playlist_side_info *psi,FILE *fp,char *path,unsigned int list_type)
{
 struct playlist_entry_info *pei;
 int j;
 char cnvtmp[MAX_ID3LEN];

 j=pds_strlen(path);

 if(j>0){ // allways have to be
  if(list_type&PLST_EXTM3U)
   fprintf(fp,"#EXTM3U\n");

  for(pei=psi->firstsong;pei<=psi->lastentry;pei++){
   if((list_type&PLST_EXTM3U) && (pei->infobits&PEIF_ENABLED)){
    fprintf(fp,"#EXTINF:%d,%s - ",
  	       (pei->timemsec+500)/1000,
               mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_ARTIST]));
    fprintf(fp,"%s\n",
               mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_TITLE]));
   }
   fprintf(fp,"%s\n",savelist_get_relative_filename(pei->filename,path,j));
  }
 }else{ // ???
  for(pei=psi->firstsong;pei<=psi->lastentry;pei++)
   fprintf(fp,"%s\n",pei->filename);         // save with full path
 }
}

static void save_mxu_playlist(struct playlist_side_info *psi,FILE *fp)
{
 struct playlist_entry_info *pei;
 char cnvtmp[MAX_ID3LEN];

 for(pei=psi->firstsong;pei<=psi->lastentry;pei++){
  fprintf(fp,"%s°%s±",(pei->filename)? pei->filename:"",
                      mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_ARTIST]));
  fprintf(fp,"%s²%8.8X\n",mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_TITLE]),
                          (pei->infobits&PEIF_ENABLED)? (MXUFLAG_ENABLED|(((pei->timemsec+500)/1000)&MXUFLAG_TIMEMASK)):0);
 }
}

static void save_cue_playlist(struct playlist_side_info *psi,FILE *fp,char *path)
{
 struct playlist_entry_info *pei;
 unsigned int pathlen=pds_strlen(path),trackcount;
 char cnvtmp[MAX_ID3LEN],lastfile[MAX_PATHNAMELEN]="";

 for(pei=psi->firstsong;pei<=psi->lastentry;pei++){
  if(pds_strcmp(pei->filename,lastfile)!=0 || !(pei->infobits&PEIF_INDEXED) || !(pei->infobits&PEIF_ENABLED)){
   char *ext=pds_strrchr(pei->filename,'.');
   if(ext){
    ext++;
    if(pds_stricmp(ext,"wav")==0)
     ext="WAVE";
   }else
    ext="";
   fprintf(fp,"FILE \"%s\" %s\n",savelist_get_relative_filename(pei->filename,path,pathlen),ext);
   pds_strcpy(lastfile,pei->filename);
   trackcount=1;
  }
  fprintf(fp,"  TRACK %2.2d AUDIO\n",trackcount++);
  if(pei->id3info[I3I_ARTIST])
   fprintf(fp,"    PERFORMER \"%s\"\n",mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_ARTIST]));
  if(pei->id3info[I3I_TITLE])
   fprintf(fp,"    TITLE \"%s\"\n",mpxplay_playlist_textconv_back(cnvtmp,pei->id3info[I3I_TITLE]));
  fprintf(fp,"    INDEX 01 %2.2d:%2.2d:%2.2d\n",(pei->pstime/60000),((pei->pstime/1000)%60),((pei->pstime%1000)*75/1000));
 }
}

char *playlist_savelist_get_savename(unsigned int list_type)
{
 switch(list_type&PLST_LISTS){
  case PLST_MXU:return mxusavename;
  case PLST_CUE:return cuesavename;
  default:return m3usavename;
 }
}

static unsigned int savelist_gettype_from_filename(char *filename)
{
 char *ext;
 ext=pds_strrchr(filename,'.');
 if(ext){
  if(pds_stricmp(ext,".m3u")==0)
   return PLST_EXTM3U;
  if(pds_stricmp(ext,".mxu")==0)
   return PLST_MXU;
  if(pds_stricmp(ext,".cue")==0)
   return PLST_CUE;
 }
 return 0;
}

unsigned int playlist_savelist_save_playlist(struct mainvars *mvp,struct playlist_side_info *psi,char *file_name,unsigned int list_type)
{
 FILE *fp;
 char filename[MAX_PATHNAMELEN],path[MAX_PATHNAMELEN];

 if(list_type){
  if(list_type&PLST_MANUAL){
   if(!psi)
    psi=mvp->psil; // playlist side ???
   if(file_name)
    pds_strcpy(filename,file_name);
   else
    pds_fullpath(filename,playlist_savelist_get_savename(list_type));
   pds_getpath_from_fullname(path,filename);
  }else{ // PLST_AUTO
   psi=mvp->psi0+1; // right side
   pds_getpath_from_fullname(path,freeopts[OPT_PROGNAME]); // get directory of mpxplay.exe
   pds_strcpy(filename,path);
   pds_strcat(filename,PDS_DIRECTORY_SEPARATOR_STR);
   pds_strcat(filename,playlist_savelist_get_savename(list_type));
  }
  if((fp=pds_fopen(filename,"wt"))!=NULL){
   switch(list_type&PLST_LISTS){
    case PLST_MXU:save_mxu_playlist(psi,fp);;break;
    case PLST_CUE:save_cue_playlist(psi,fp,path);;break;
    default:save_m3u_playlist(psi,fp,path,list_type);;break;
   }
   fclose(fp);
   return 1;
  }
 }
 return 0;
}

static char savelist_filename[MAX_PATHNAMELEN],savelist_lastfilename[MAX_PATHNAMELEN];
static unsigned int savelist_type;

static void playlist_savelist_manualsave(struct mainvars *mvp)
{
 char *sn,*fn,msg[MAX_PATHNAMELEN+32];

 if(savelist_type || (pds_stricmp(savelist_filename,savelist_lastfilename)==0)){ // filetype was selected or filename was not modified
  // correct file-extension for list_type (.M3U,.MXU,.CUE)
  sn=playlist_savelist_get_savename(savelist_type);
  sn=pds_strrchr(sn,'.');
  if(sn){
   fn=pds_strrchr(savelist_filename,'.');
   if(fn){
    *fn=0;
    pds_strcpy(fn,sn);
   }
  }
 }else{
  // correct list_type for file-extension
  savelist_type=savelist_gettype_from_filename(savelist_filename);
 }

 if(playlist_savelist_save_playlist(mvp,mvp->psie,savelist_filename,(savelist_type|PLST_MANUAL))){
  pds_strcpy(msg,"Playlist is saved to\n");
  pds_strcat(msg,savelist_filename);
  display_textwin_openwindow_keymessage(TEXTWIN_FLAG_TIMEDMESSAGE|TEXTWIN_FLAG_MSGCENTERALIGN,NULL,msg);
 }else{
  pds_strcpy(msg,"Couldn't save playlist to\n");
  pds_strcat(msg,savelist_filename);
  display_textwin_openwindow_errormsg_ok(NULL,msg);
 }
}

static display_textwin_button_t savelist_buttons[]={
 {" M3U "   ,0x326d}, // 'm'
 {""        ,0x324d}, // 'M'
 {" EXTM3U ",0x1265}, // 'e'
 {""        ,0x1245}, // 'E'
 {" CUE "   ,0x2e63}, // 'c'
 {""        ,0x2e43}, // 'C'
 {" MXU "   ,0x2d78}, // 'x'
 {""        ,0x2d58}, // 'X'
 {" Cancel ",KEY_ESC}, // ESC
 {NULL,0}
};

void manual_savelist_keyhand(struct mainvars *mvp,unsigned int extkey)
{
 switch(extkey){
  case 0x326d:
  case 0x324d:savelist_type=0;break;
  case 0x1265:
  case 0x1245:savelist_type=PLST_EXTM3U;break;
  case 0x2e63:
  case 0x2e43:savelist_type=PLST_CUE;break;
  case 0x2d78:
  case 0x2d58:savelist_type=PLST_MXU;break;
  default:return;
 }
 playlist_savelist_manualsave(mvp);
}

void playlist_savelist_manual_save(struct mainvars *mvp)
{
 void *tw;
 unsigned int side,type;
 struct display_textwin_button_t *btsel;
 char filename[MAX_PATHNAMELEN],msg[50];

 if(savelist_filename[0]){
  pds_strcpy(filename,pds_getfilename_from_fullname(savelist_filename));
  pds_fullpath(savelist_filename,filename); // new path + old filename
 }else{ // first calling
  if(mvp->psie==mvp->psil){ // create listname from input file (if it was playlist)
   type=savelist_gettype_from_filename(playlist_loadsub_getinputfile(mvp->psie));
   if(type){
    savelist_type=type;
    pds_fullpath(savelist_filename,playlist_loadsub_getinputfile(mvp->psie));
   }
  }
  if(!savelist_filename[0])
   pds_fullpath(savelist_filename,playlist_savelist_get_savename(savelist_type));
 }

 pds_strcpy(savelist_lastfilename,savelist_filename);

 switch(savelist_type&PLST_LISTS){
  case PLST_EXTM3U:btsel=&savelist_buttons[2];break;
  case PLST_CUE:btsel=&savelist_buttons[4];break;
  case PLST_MXU:btsel=&savelist_buttons[6];break;
  default:btsel=&savelist_buttons[0];
 }

 tw=display_textwin_allocwindow_items(TEXTWIN_FLAG_MSGCENTERALIGN," Savelist ",manual_savelist_keyhand,mvp);
 side=mvp->psie-mvp->psi0; // editorside
 sprintf(msg," Save playlist (%s side) to",((side)? "right":"left"));
 display_textwin_additem_msg_alloc(tw,0,0,-1,msg);
 display_textwin_additem_editline(tw,TEXTWIN_FLAG_MSGCENTERALIGN,0,-1,40,&savelist_filename[0],MAX_PATHNAMELEN-2);
 display_textwin_additem_separatorline(tw,-1);
 display_textwin_additem_buttons(tw,TEXTWIN_FLAG_MSGCENTERALIGN,0,-1,savelist_buttons,btsel);
 display_textwin_openwindow_items(tw,0,0,0);
}
