<?php

class m130508_153437_instalarUsuarios extends CDbMigration {

    protected $MySqlOptions = 'ENGINE=InnoDB CHARSET=utf8';
    private $_model;

    public function safeUp() {
        if (!Yii::app()->getModule('usuario')) {
            echo "\n\nAñadir a console.php :\n"
            . "'modules'=>array(\n"
            . "...\n"
            . "    'usuario'=>array(\n"
            . "        ... # copiar configuración de main.php\n"
            . "    ),\n"
            . "...\n"
            . "),\n"
            . "\n";
            return false;
        }
        Yii::import('usuario.models.Usuario');
        
        switch ($this->dbType()) {
            case "mysql":
                // Usuarios
                $this->createTable(Yii::app()->getModule('usuario')->tablaUsuarios, array(
                    "id" => "pk",
                    "username" => "varchar(20) NOT NULL DEFAULT ''",
                    "password" => "varchar(128) NOT NULL DEFAULT ''",
                    "email" => "varchar(128) NOT NULL DEFAULT ''",
                    "clave_activacion" => "varchar(128) NOT NULL DEFAULT ''",
                    "fecha_registro" => "TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP",
                    "fecha_borrado" => "TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00'",
                    "ultima_visita" => "TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00'",
                    "superusuario" => "int(1) NOT NULL DEFAULT 0",
                    "estado" => "int(1) NOT NULL DEFAULT 0",
                ), $this->MySqlOptions);
                
                $this->createIndex('usuario_username', Yii::app()->getModule('usuario')->tablaUsuarios, 'username', true);
                $this->createIndex('usuario_email', Yii::app()->getModule('usuario')->tablaUsuarios, 'email', true);
                $this->createIndex('usuario_superusuario', Yii::app()->getModule('usuario')->tablaUsuarios, 'superusuario', false);
                $this->createIndex('usuario_estado', Yii::app()->getModule('usuario')->tablaUsuarios, 'estado', false);
                
               // Perfiles
                $this->createTable(Yii::app()->getModule('usuario')->tablaPerfiles, array(
                    'usuario_id' => 'pk',
                    'nombre' => 'string',
                    'apellidos' => 'string',
                ), $this->MySqlOptions);
                
                $this->addForeignKey('usuario_perfil_id', Yii::app()->getModule('usuario')->tablaPerfiles, 'usuario_id', Yii::app()->getModule('usuario')->tablaUsuarios, 'id', 'CASCADE', 'RESTRICT');
                
                // Campos de perfil
                $this->createTable(Yii::app()->getModule('usuario')->tablaCamposPerfiles, array(
                    "id" => "pk",
                    "varname" => "varchar(50) NOT NULL DEFAULT ''",
                    "title" => "varchar(255) NOT NULL DEFAULT ''",
                    "field_type" => "varchar(50) NOT NULL DEFAULT ''",
                    "field_size" => "int(3) NOT NULL DEFAULT 0",
                    "field_size_min" => "int(3) NOT NULL DEFAULT 0",
                    "required" => "int(1) NOT NULL DEFAULT 0",
                    "match" => "varchar(255) NOT NULL DEFAULT ''",
                    "range" => "varchar(255) NOT NULL DEFAULT ''",
                    "error_message" => "varchar(255) NOT NULL DEFAULT ''",
                    "other_validator" => "text",
                    "default" => "varchar(255) NOT NULL DEFAULT ''",
                    "widget" => "varchar(255) NOT NULL DEFAULT ''",
                    "widgetparams" => "text",
                    "position" => "int(3) NOT NULL DEFAULT 0",
                    "visible" => "int(1) NOT NULL DEFAULT 0",
                ), $this->MySqlOptions);
                break;
        }

        if (in_array('--interactive=0', $_SERVER['argv'])) {
            $this->_model->username = 'admin';
            $this->_model->email = 'webmaster@example.com';
            $this->_model->password = 'admin';
        } else {
            $this->readStdinUser('Admin login', 'username', 'admin');
            $this->readStdinUser('Admin email', 'email', 'webmaster@example.com');
            $this->readStdinUser('Admin password', 'password', 'admin');
        }

        $this->insert(Yii::app()->getModule('usuario')->tablaUsuarios, array(
            "id" => "1",
            "username" => $this->_model->username,
            "password" => Yii::app()->getModule('usuario')->cifrar($this->_model->password),
            "email" => $this->_model->email,
            "clave_activacion" => Yii::app()->getModule('usuario')->cifrar(microtime()),
            "fecha_registro" => date('Y-m-d H:i:s'),
            "superusuario" => "1",
            "estado" => Usuario::ESTADO_ACTIVO,
        ));
        
        $this->insert(Yii::app()->getModule('usuario')->tablaPerfiles, array(
            "usuario_id" => "1",
            "nombre" => "Administrator",
            "apellidos" => "Admin",
        ));

        $this->insert(Yii::app()->getModule('usuario')->tablaCamposPerfiles, array(
            "id" => "1",
            "varname" => "nombre",
            "title" => "Nombre",
            "field_type" => "VARCHAR",
            "field_size" => "255",
            "field_size_min" => "3",
            "required" => "2",
            "match" => "",
            "range" => "",
            "error_message" => "Incorrect First Name (length between 3 and 50 characters).",
            "other_validator" => "",
            "default" => "",
            "widget" => "",
            "widgetparams" => "",
            "position" => "1",
            "visible" => "3",
        ));
        $this->insert(Yii::app()->getModule('usuario')->tablaCamposPerfiles, array(
            "id" => "2",
            "varname" => "apellidos",
            "title" => "Apellidos",
            "field_type" => "VARCHAR",
            "field_size" => "255",
            "field_size_min" => "3",
            "required" => "2",
            "match" => "",
            "range" => "",
            "error_message" => "Incorrect Last Name (length between 3 and 50 characters).",
            "other_validator" => "",
            "default" => "",
            "widget" => "",
            "widgetparams" => "",
            "position" => "2",
            "visible" => "3",
        ));
    }

    public function safeDown() {
        $this->dropTable(Yii::app()->getModule('usuario')->tablaCamposPerfiles);
        $this->dropTable(Yii::app()->getModule('usuario')->tablaPerfiles);
        $this->dropTable(Yii::app()->getModule('usuario')->tablaUsuarios);
    }

    public function dbType() {
        list($type) = explode(':', Yii::app()->db->connectionString);
        echo "type db: " . $type . "\n";
        return $type;
    }

    private function readStdinUser($prompt, $field, $default = '') {
        if (!$this->_model)
            $this->_model = new Usuario;

        while (!isset($input) || !$this->_model->validate(array($field))) {
            echo $prompt . (($default) ? " [$default]" : '') . ': ';
            $input = (trim(fgets(STDIN)));
            if (empty($input) && !empty($default)) {
                $input = $default;
            }
            $this->_model->setAttribute($field, $input);
        }
        return $input;
    }

}