<?php

class AutomaticRecordExportCommand extends CConsoleCommand
{

    protected $date;
    protected $deleteAfterExport = false;
    protected $zipFileName;
    protected $recordFileDatas = array();

    public function run($args)
    {
        try {
            $this->initAutomatedExport($args);
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
    }

    protected function initAutomatedExport($args)
    {
        $this->initCommandLineParameters($args);
        $this->automatedRecordExport();
    }

    protected function initCommandLineParameters($args)
    {
        $params = $this->parseCommandLineParameters($args);

        $this->setDate(@$params['-date']);
        $this->setDeleteAfterDownloadFlag(@$params['-delete']);
        $this->setZipArchiveName();
    }

    protected function parseCommandLineParameters($args)
    {
        $params = array();
        foreach ($args as $key => $param) {
            if (strpos($param, '-') === 0 && isset($args[($key + 1)])) {
                $params[$param] = $args[($key + 1)];
            }
        }
        return $params;
    }

    protected function setDate($date)
    {
        if (!isset($date) || empty($date)) {
            $date = substr(PhonalisaDate::newServerDate(), 0, 10);
        }
        if (strtolower($date) == 'all') {
            $date = strtolower($date);
        }
        $this->date = $date;
    }

    protected function setDeleteAfterDownloadFlag($deleteAfterExport = '')
    {
        if (strtolower($deleteAfterExport) == 'true') {
            $deleteAfterExport = true;
        } else {
            $deleteAfterExport = false;
        }
        $this->deleteAfterExport = $deleteAfterExport;
    }

    protected function setZipArchiveName()
    {
        $newServerDateTime = PhonalisaDate::newServerDate();
        $dateTime = $this->replaceEmptySpaceAndColonInDateTime($newServerDateTime);

        $this->zipFileName = 'phonalisa-record-archive_' . $dateTime . '.zip';
    }

    protected function replaceEmptySpaceAndColonInDateTime($dateTime)
    {
        $searchArray = array(' ', ':');
        $replaceWithArray = array('_', '-');

        return str_replace($searchArray, $replaceWithArray, $dateTime);
    }

    protected function automatedRecordExport()
    {
        $limit = 1000;
        $offset = 0;

        $foundItem = true;
        while ($items = UCItem::model()->find(array('typ' => 'callrecording'), 'timestamp DESC', $limit, $offset)) {
            $foundItem = $this->processItems($items);
            if ($foundItem == false) {
                break;
            }
            $offset += $limit;
        }
        $this->exportZipArchive();
        $this->showSummaryTextForExportetFiles();
    }

    protected function processItems($items)
    {
        foreach ($items as $item) {
            if ($this->processSearchForItems($item) == false) {
                return false;
            }
        }
        return true;
    }

    protected function processSearchForItems($item)
    {
        $date = $this->date;
        if ($date == 'all') {
            $this->processItemOutput($item);
            return true;
        } else if (substr($item->timestamp, 0, 10) == $date) {
            $this->processItemOutput($item);
            return true;
        } else {
            return false;
        }
    }

    protected function processItemOutput($item)
    {
        $recordFileName = $this->getRecordFileName($item);
        $binaryData = $this->getRecordBinaryData($item);

        $this->recordFileDatas[$recordFileName] = $binaryData;
        $this->deleteItemIfRequested($item);
    }

    protected function getRecordFileName($item)
    {
        $timestamp = $item->timestamp;
        $dateTime = $this->replaceEmptySpaceAndColonInDateTime($timestamp);
        $userExtension = $this->getUserExtensionForItem($item);

        $fileName = "phonalisa-record-file_" . $dateTime . "_" . $userExtension . ".wav";
        return $fileName;
    }

    protected function getUserExtensionForItem($item)
    {
        $userExtension = User::model()->findByPk($item->owner_id);

        return $userExtension->extension;
    }

    protected function getRecordBinaryData($item)
    {
        $length = 0;
        $data = "";
        $binaryField = "record_data";

        $item->getBinaryField($binaryField, $data, $length);

        return $data;
    }

    protected function exportZipArchive()
    {
        $files = $this->recordFileDatas;
        $zipFileName = $this->zipFileName;
        $zip = new ZipArchive;
        $zip->open($zipFileName, ZipArchive::CREATE);
        foreach ($files as $fileName => $fileBinaryData) {
            $zip->addFromString($fileName, $fileBinaryData);
        }
        $zip->close();
    }

    protected function deleteItemIfRequested($item)
    {
        $deleteDataFromSource = $this->deleteAfterExport;
        if (strtolower($deleteDataFromSource) == true) {
            $item->delete();
        }
    }

    protected function showSummaryTextForExportetFiles()
    {
        $recordFilesCount = count($this->recordFileDatas);

        if ($recordFilesCount == 0) {
            echo "No file for this date found!\n";
        } else {
            echo "Exported files: $recordFilesCount\n";
        }
    }
}
