<?php
/**
 * Created by PhpStorm.
 * User: Saruti
 * Date: 10/25/2015
 * Time: 11:28 AM
 */
namespace App\Templater;

use File;
use Illuminate\Support\Str;
use Psy\Exception\ErrorException;

class StorageManager
{
    public function __construct()
    {
        \DB::getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
        $this->updateModels();
    }

    private $store_path = "templater\\";
    private $model_storage = 'models.php';

    private function getStorage($store_name)
    {
        switch ($store_name) {
            case 'models':
                return $this->store_path . $this->model_storage;
        }
        return null;
    }

    public
    function updateModels()
    {
        /**
         * Check if the model properties storage file exists
         */
        if (!File::exists($this->getStorage('models'))) {
            $model_collection = new \stdClass;
            $model_collection->migration_batch = \DB::table('migrations')->select(['batch'])->max('batch');
            $model_collection->models = [];
            foreach (\DB::getDoctrineSchemaManager()->listTableNames() as $table) {
                $model = new \stdClass;
                $model->title = ucwords(str_replace(['id', 'file', 'date'], '', str_replace("_", " ", $table)));
                $model->properties = [];
                foreach (\Schema::getColumnListing($table) as $column) {
                    $property = new \stdClass;
                    $property->displayName = ucwords(str_replace(['id', 'file', 'date'], '', str_replace("_", " ", $column)));
                    $property->type = \DB::connection()->getDoctrineColumn($table, $column)->getType()->getName();
                    $property->name = $column;
                    $property->extras = null;
                    $model->properties[$column] = $property;
                }
                $model_collection->models[Str::singular($table)] = $model;
            }
            File::put(storage_path($this->getStorage('models')), json_encode($model_collection));
        }
    }

    private
    function validateModelProperties()
    {

    }

    protected
    function getModel($name)
    {
        $model_collection = $this->readModels();
        if (!$model_collection->migration_batch != \DB::table('migrations')->select(['batch'])->max('batch')) {
            $this->updateModels();
            $model_collection = $this->readModels();
        }
        $mc = (array)($model_collection->models);
        if (in_array($name, array_keys($mc)))
            return $mc[$name];
        else
            ErrorException::throwException(12221, 'Not found', 'StorageManager', 79);
    }

    private
    function readModels()
    {
        return json_decode(File::get(storage_path($this->getStorage('models'))));
    }
}