//
// C++ Implementation: gigamanager
//
// Description: 
//
//
// Author: Predrag Viceic <viceic@net2000.ch>, (C) 2005
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "gigamanager.h"

GigaManager::GigaManager(QObject *parent, const char *name)
 : QObject(parent, name)
{
}


GigaManager::~GigaManager()
{
}

void GigaManager::writeGigaFile(QString path_and_filename,QStringList* filenames,QValueList <beatline_data> bld){
    QString filename=QFileInfo(path_and_filename).fileName();
    QString dirpath=QFileInfo(path_and_filename).dirPath();
    char nb_keygroups=filenames->size();
    qHeapSort(bld);
    IpatchFile *file;
    IpatchGigFile *gigfile;
    IpatchGigInst *inst;
    IpatchGigSample *sample;
    IpatchGigRegion *region;
    IpatchConverter *conv;
    GError *err = NULL;
    char  *name;
    
    /* initialize libInstPatch */
    ipatch_init ();
    IpatchGig* gig = ipatch_gig_new ();	/* ++ ref new Gig object */
    /*create new Gig instrument (++ ref) */
    inst = ipatch_gig_inst_new ();
    /* set instrument name */

    /* append instrument to Gig (ensure that its name is unique) */
    ipatch_container_add_unique (IPATCH_CONTAINER (gig),IPATCH_ITEM (inst));
    
     
    for (int i=0;i<nb_keygroups;i++){
        QString temp_filename=filenames->operator[](i);
        temp_filename.prepend(dirpath+"/");
        int midiNote=bld[i].midiNote;
        if (midiNote==-1){
            cout<<"file: "<<temp_filename<<" midi: "<<midiNote<<"\n";
            continue;
        }
        /* identify and open file (++ new object reference) */
        file = ipatch_file_identify_open (temp_filename.ascii(), "r", &err);
        if (!file){
	  fprintf (stderr, "Failed to identify file '%s': %s\n", temp_filename.ascii(),
		   ipatch_gerror_message (err));
	  g_clear_error (&err);
	  continue;
	}
	
	/* attempt to convert file to GigSample */
	sample = (IpatchGigSample *)ipatch_convert_object_to_type (G_OBJECT (file), IPATCH_TYPE_GIG_SAMPLE, &err);

	if (!sample)
        {
            fprintf (stderr,
                    "Failed to convert sample file '%s' to Gig sample: %s\n",
                    filename.ascii(), ipatch_gerror_message (err));

            g_clear_error (&err);
            g_object_unref (file); /* -- unref file */
    
            continue;
        }
    
    //    region=ipatch_gig_region_new (); /* ++ ref new Giga region */
	
	//ipatch_container_add (IPATCH_CONTAINER (inst), IPATCH_ITEM (region));
/*
        IpatchRange* range=ipatch_range_new();
        range->low=midiNote;
        range->high=midiNote;
        g_object_set(region,"key-range", range, NULL);
    
        ipatch_range_free(range);
  */      
        
	
	
    }

}
