/*
 
This SOURCE CODE is provided AS IS with NO WARRANTY OF ANY KIND, so always take a backup of your files first
@auther Mohammed Hewedy
*/
  
#include <iostream>
#include <cstring>

#include <taglib/fileref.h>
#include <taglib/tag.h>

#include <dirent.h>

using namespace std;
using namespace TagLib;

void modifyID3Data(char*, char*, char*);
void usage();
char* extractSongName(char* songName, char* fileName);
char* obtainFullPath(char* fullPath, char* dirName, char* FileName);

int main(int argc, char** argv)
{
    if (argc != 3)
        usage();
    
    char* dirName = argv[1];
    DIR* d = opendir(dirName);
    
    char* artist = argv[2];
    
    if (d)
    {
        dirent* dn;
        
        while ( dn = readdir(d))
        {
            if (dn->d_type == DT_REG)
            {
                char* fileName = dn->d_name;
                
                char fullPath[strlen(dirName) + strlen(fileName) + 1];
                obtainFullPath(fullPath, dirName, fileName);
                
                char songName[strlen(fileName)-3];
                extractSongName(songName, fileName);
                
                modifyID3Data(fullPath, artist, songName);
                cout <<"Updating " << fileName <<endl;
            }
        }
        
        closedir(d);
    }
    
    return 0;
}

char* obtainFullPath(char* fullPath, char* dirName, char* fileName)
{
    strcpy(fullPath, dirName);
    strcpy(&fullPath[strlen(dirName)], fileName);
    
}

char* extractSongName(char* songName, char* fileName)
{
    int l = strlen(fileName);
    strncpy(songName, fileName, l-4);
    songName[l-4] = '\0';
    return songName;
}

void modifyID3Data(char* fullFilePath, char* artist, char* songName)
{
    
    FileRef f(fullFilePath);
    cout << f.tag()->artist() << endl;
    f.tag()->setArtist(artist);
    f.tag()->setTitle(songName);
    f.save();
    
}

void usage()
{
    char* appName = "tagEditor";
    char* desc = "updates a bulk of Dir of MP3 Files (and other formats, see http://developer.kde.org/~wheeler/taglib.html) "
            "sets the Artist with <artist> and set the song title by its file name execluding the four character extentions";
    char* disc = "This Program is provided AS IS with NO WARRANTY OF ANY KIND, so always take a backup of your files first.";
    cout << "Usage: " << appName << " <dir> <artist>" <<endl << desc << endl << endl << disc << endl;
    exit(1);
}