<?php
//@*--


class Theme_Designer_Model_Export_Chunk
{
    private $_lastChunk = null;
    private $_chunkFolder = '';
    private $_lockFile = '';
    private $_isLast = false;

    public function save($info) {
        $this->validate($info);

        $this->_lastChunk = $info;
        $this->_chunkFolder = MAGENTO_ROOT . Mage::getSingleton('designer/config')->get('paths/export/upload') . DS . $info['id'];
        $this->_lockFile = $this->_chunkFolder . '/lock';

        if (!is_dir($this->_chunkFolder)) {
            @mkdir($this->_chunkFolder, 0777, true);
        }

        $f = fopen($this->_lockFile, 'c');

        if (flock($f, LOCK_EX)) {
            $chunks = array_diff(scandir($this->_chunkFolder), array('.', '..', 'lock'));

            if ((int) $this->_lastChunk['total'] === count($chunks) + 1) {
                $this->_isLast = true;
            } else {
                file_put_contents($this->_chunkFolder . '/' . (int) $info['current'], $info['content']);
            }
            flock($f, LOCK_UN);
        } else {
            throw new Mage_Adminhtml_Exception('Couldn\'t lock the file');
        }
    }

    public function last() {
        return $this->_isLast;
    }

    public function complete() {
        $content = '';
        for ($i = 1, $count = (int) $this->_lastChunk['total']; $i <= $count; $i++) {
            if ((int) $this->_lastChunk['current'] === $i) {
                $content .=  $this->_lastChunk['content'];
            } else {
                if (!file_exists($this->_chunkFolder . "/$i"))
                    throw new Mage_Adminhtml_Exception('Missing chunk #' . $i . ' : ' . implode(' / ', scandir($this->_chunkFolder)));
                $content .= file_get_contents($this->_chunkFolder . "/$i");
            }
        }
        Mage::helper('designer/filesystem')->remove($this->_chunkFolder, true);
        return $content;
    }

    private function validate($info) {
        if (!isset($info['id']) || !$info['id'])
            throw new Mage_Adminhtml_Exception('Invalid id');
        if (!isset($info['total']) || (int) $info['total'] < 1)
            throw new Mage_Adminhtml_Exception('Invalid chunks total');
        if (!isset($info['current']) || (int) $info['current'] < 1)
            throw new Mage_Adminhtml_Exception('Invalid current chunk number');
        if (!isset($info['content']) || !strlen($info['content']))
            throw new Mage_Adminhtml_Exception('Invalid chunk content');
    }

}
//--*@