<?php

class IcsvForm extends CFormModel
{

    public $lang;
    public $import;
    public $fileMaxSize = 10485760; /* 1024 * 1024 * 10 - 10 MB */
    public $fileMaxSizeMessage = 10; /* 10 MB */
    public $csvPath;
    public $assetsPath;

    public function init()
    {
        $this->preparePaths();
//        $this->publishAssets();

        $fileMaxSize['postSize'] = toBytes(ini_get('post_max_size'));
        $fileMaxSize['uploadSize'] = toBytes(ini_get('upload_max_filesize'));
        $this->fileMaxSize = min($fileMaxSize);
        $this->fileMaxSizeMessage = self::formatBytes($this->fileMaxSize);

        parent::init();
    }

    public function preparePaths()
    {
        $this->assetsPath = Yii::getPathOfAlias('application.modules.iecsv.assets');
        $this->csvPath = Yii::getPathOfAlias('webroot.uploads.iecsv');
    }

    public function rules()
    {
        $rules = array(
            array(
                'import', 'file',
                'types' => 'csv, zip',
                'maxSize' => $this->fileMaxSize,
                'tooLarge' => Yii::t('module_iecsv', 'The file was larger than {size}. Please upload a smaller file.', array('{size}' => $this->fileMaxSizeMessage)),
                'on' => 'insert',
            ),
        );

        return $rules;
    }

    public static function formatBytes($size, $precision = 2)
    {
        $base = log($size) / log(1024);
        $suffixes = array('', 'k', 'M', 'G', 'T');

        return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
    }
}
