<?php 
    # $Id: benchmarkInstance_ADD.php,v 1.6 2007/01/14 15:53:11 jarda Exp $

    /* This page adds a new benchmark instance
     */

    require_once('structuredPage.inc.php');

    class PageClass extends EditDBStructuredPage 
    {
        
        function getTitle()
        {
            return 'Benchmark instance addition';
        }
            

        function createPage()
        {
            if ($_POST["OK"])
            {
                $db = connect();

                # upload the file if specified
                if ($_FILES['uploadedFile'] && $_FILES['uploadedFile']['name']) {
                    $uploadDirectoryName = $this->getUploadDirectoryName($db);
                    
                    $fileName = $this->getUploadedFileName($db, $uploadDirectoryName, $_POST['benchmarkName'], $_POST['formatId']);

                    $this->uploadFile($uploadDirectoryName, $fileName);
                }
                else {
                    $fileName = "";
                }

                # start transaction
                $db->StartTrans();
                
                $benchmarkId = $this->getBenchmarkId($db, $_POST['benchmarkName']);

                # create benchmark if necessary
                if (!$benchmarkId)
                    $benchmarkId = $this->createBenchmark($db, $_POST['benchmarkName'], $_POST['benchmarkDescription']);

                $benchmarkInstanceId = $this->createBenchmarkInstance($db, $benchmarkId, $_POST['formatId'],
                                                               $_POST['benchmarkInstanceDescription'], 
                                                               $_POST['benchmarkSetId'], $fileName);

                $this->createAttributes($db, $benchmarkInstanceId, $_POST);

                # complete transaction
                $db->CompleteTrans();

                # parse the file if specified
                if ($_FILES['uploadedFile']) {
                    if ($_POST['parse']) {
                        exec(BenchConfig::$pythonBinary . " " . BenchConfig::$execDirectory . 
                             "/BenchmarkFiller.py -f $uploadDirectoryName/$fileName -i $benchmarkInstanceId");
                    }
                }
            }

            header("Location: index.php"); /* Redirect browser */ 
        }


        /* Returns proper file name for the uploaded file
        */
        function getUploadedFileName($db, $uploadDirectoryName, $benchmarkName, $formatId)
        {
            $query = "SELECT name FROM format WHERE id = $formatId";
            
            $recordSet = $db->Execute($query);
            
            $row = $recordSet->FetchRow();

            $extension = strtolower($row['name']);

            $fileName = "$benchmarkName.$extension";

            if (!file_exists("$uploadDirectoryName/$fileName"))
                return $fileName;

            $index = 1;

            while (True) {
                $fileName = "$benchmarkName.$extension";

                if (!file_exists("$uploadDirectoryName__$index/$fileName"))
                    return $fileName;
                
                $index++;
            }
        }


        /* Returns benchmark ID or NULL if there is no corresponding benchmark yet
        */
        function getBenchmarkId($db, $name)
        {
            $recordSet = $db->Execute("SELECT * FROM benchmark WHERE name='$name'");
            if (!$recordSet->RecordCount())
                return NULL;

            $row = $recordSet->FetchRow();

            return $row['id'];
        }


        /* Creates a benchmark table entry
        */
        function createBenchmark($db, $name, $description)
        {
            $benchmarkId = $db->GenId("benchmark_id_seq"); 
            
            $query = "INSERT INTO benchmark (id, name, description) VALUES ($benchmarkId, '$name', '$description')";

            $result = $db->Execute($query);

            return $benchmarkId;
        }


        /* Creates a benchmark instance table entry
        */
        function createBenchmarkInstance($db, $benchmarkId, $formatId, $description, $benchmarkSetId, $fileName)
        {
            $benchmarkInstanceId = $db->GenId("benchmarkinstance_id_seq");
            
            $query = "INSERT INTO benchmarkInstance " .
                     "(id, benchmarkId, formatId, description, benchmarkSetId, fileName) " .
                     "VALUES ($benchmarkInstanceId, $benchmarkId, $formatId, '$description', $benchmarkSetId, '$fileName')";

            $result = $db->Execute($query);

            return $benchmarkInstanceId;
        }

        /* Creates all benchmark instance attributes
        */
        function createAttributes($db, $benchmarkInstanceId, $attributesArray)
        {
            // Could be optimized, see adodb - insert with 2d arrays
            foreach ($attributesArray as $key => $value) {
                if (preg_match('/attribute_(\d+)/', $key, $results) && $value) {
                    $query = "INSERT INTO benchmarkInstanceAttribute (benchmarkInstanceId, attributeId, value) ".
                        "VALUES ($benchmarkInstanceId, $results[1], $value)";
                    $db->Execute($query);
                }
            }
        }


        # XXX: move to some common include module?
        function getUploadDirectoryName($db)
        {
            $benchmarkSetName = $this->getBenchmarkSetName($db);

            return BenchConfig::$benchmarkFilesDirectory . "/$benchmarkSetName";
        }


        /* Upload the file
        */
        function uploadFile($uploadDirectoryName, $fileName)
        {
            if (!file_exists($uploadDirectoryName))
                mkdir($uploadDirectoryName, 0755, 1);

            $destination = "$uploadDirectoryName/$fileName";

            if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $destination)) {
            } 
            else{
                echo "There was an error uploading the file, please try again!";
            }
        }


        /* Returns benchmark set name by its ID
        */
        function getBenchmarkSetName($db)
        {
            $query = "SELECT name FROM benchmarkSet WHERE id = $_POST[benchmarkSetId]";
            
            $recordSet = $db->Execute($query);
            
            $row = $recordSet->FetchRow();
            return $row['name'];
        }

        function checkEnvironment()
        {
            return ($_POST['benchmarkSetId'] && $_POST['formatId'] && $_POST['benchmarkName']);
        }
    }

    launchPage();

    # vim:enc=iso8859-2:fenc=iso8859-2:
?>
