<?php

require_once __DIR__ . '/../models/CDR.php';

class AutomaticCsvExportCommand extends CConsoleCommand
{

    protected $date;
    protected $downloadFile = false;
    protected $deleteAfterExport = false;
    protected $delimiter = ';';
    protected $fileName = 'phonalisa_automaticCdrExport.csv';
    protected $attributes = array(
        'start_timestamp',
        'source',
        'target',
        'type',
        'duration',
        'did',
        'meta'
    );
    protected $attributeLabels = array(
        'start_timestamp' => 'Date/Time',
        'source' => 'Source',
        'target' => 'Target',
        'type' => 'Type',
        'duration' => 'Duration',
        'did' => 'DID',
        'meta' => 'Meta'
    );

    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->automatedCdrExport();
    }

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

        if (!$this->tokenIsValid(@$params['-token'])) {
            throw new Exception('Invalid Token');
        }

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

    protected function tokenIsValid($token)
    {
        $cfgToken = cfg('CDR_EXPORT_AUTHTOKEN');

        if ($cfgToken === '') {
            return true;
        }

        if ($token !== $cfgToken) {
            return false;
        }
        return true;
    }

    protected function setDate($date)
    {
        if (!isset($date) || empty($date)) {
            $date = PhonalisaDate::convertServerDateTo("Y-m-d");
        }
        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 setDownloadFlag($downloadFile = '')
    {
        if (strtolower($downloadFile) == 'true') {
            $downloadFile = true;
        } else {
            $downloadFile = false;
        }
        $this->downloadFile = $downloadFile;
    }

    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 automatedCdrExport()
    {
        $limit = 1000;
        $offset = 0;
        $this->setHeaderForExportFile();

        $foundItem = true;
        while ($items = CDR::model()->find(array(), 'start_timestamp DESC', $limit, $offset)) {
            $foundItem = $this->processItems($items);
            if ($foundItem == false) {
                break;
            }
            if (!$this->deleteAfterExport) {
                $offset += $limit;
            }
        }
    }

    protected function setHeaderForExportFile()
    {
        if ($this->downloadFile) {
            $this->printHeaderForFileDownload();
        } else {
            $this->printHeaderInFile();
        }
    }

    protected function printHeaderForFileDownload()
    {
        $attributeLabels = $this->getAttributeLabels();
        $delimiter = $this->delimiter;
        $fileName = $this->fileName;

        header('Content-type: text/csv');
        header("Content-disposition: attachment; filename=$fileName");
        header("Pragma: no-cache");
        header("Expires: 0");
        print(implode($delimiter, $attributeLabels));
    }

    protected function getAttributeLabels()
    {
        $attributes = $this->attributes;
        $attributeLabels = array();
        foreach ($attributes as $attribute) {
            $allAttributeLabels = $this->attributeLabels;
            $attributeLabels[] = $allAttributeLabels[$attribute];
        }
        return $attributeLabels;
    }

    protected function printHeaderInFile()
    {
        $attributeLabels = $this->getAttributeLabels();
        $delimiter = $this->delimiter;
        $file = $this->getFilePathForAutomaticExport();

        $handle = fopen($file, "w");
        fputcsv($handle, $attributeLabels, $delimiter);
        fclose($handle);
    }

    protected function getFilePathForAutomaticExport()
    {
        $fileName = $this->fileName;
        $path = Yii::app()->getRuntimePath() . '/cdrexport';

        if (!file_exists($path)) {
            mkdir($path);
        }
        return "$path/$fileName";
    }

    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' || substr($item->start_timestamp, 0, 10) == $date) {
            $this->processItemOutput($item);
            return true;
        } else {
            return false;
        }
    }

    protected function processItemOutput($item)
    {
        if ($this->downloadFile) {
            echo $this->downloadExportData($item);
        } else {
            $this->writeExportDataToFile($item);
        }
        $this->deleteItemIfRequested($item);
    }

    protected function downloadExportData($item)
    {
        $exportData = "\n";
        $delimiter = $this->delimiter;
        $csvHeader = $this->attributes;

        foreach ($csvHeader as $attribute) {
            $exportData .= $item->$attribute . $delimiter;
        }
        return $exportData;
    }

    protected function writeExportDataToFile($item)
    {
        $fileName = $this->getFilePathForAutomaticExport();
        $delimiter = $this->delimiter;
        $handle = fopen($fileName, "a");

        $itemAttributes = $this->returnAllCdrItemAttributes($item);

        fputcsv($handle, $itemAttributes, $delimiter);
        fclose($handle);
    }

    protected function returnAllCdrItemAttributes($item)
    {
        $attributes = $this->attributes;
        $itemAttributes = array();
        foreach ($attributes as $attribute) {
            $allItemAttributes = $item->attributes;
            $itemAttributes[] = $allItemAttributes[$attribute];
        }
        return $itemAttributes;
    }

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