<?php

namespace Teknisa\Libs\Service;

use Teknisa\Libs\Util\Utilities;
use Teknisa\Libs\Util\Repositories\Migration as MigrationRepository;
use Teknisa\Libs\Util\InstanceProvider;

class Version {

    CONST TEKNISA_ENTITIES = 'git@192.168.122.56:teknisa/entities.git';

    public function getVersionInfo($currentModule) {
        $versionInfo = array(
            'name' => "",
			'version' => "",
			'dependencies' => array(
                'frontend' => array(),
				'backend'  => array(),
				'modules'  => array(),
            )
        );
        $config      = Utilities::getLoginConfig();
        $modulesPath = $config['modulesPath'];
        $productPath = Utilities::getProductBasePath();
        $modules     = $this->getFileContentsDecoded($productPath . $modulesPath);
        foreach($modules as $module => $moduleInfo) {
            if(!isset($moduleInfo['onlyControl']) && !isset($moduleInfo['nextProduct']) && !isset($moduleInfo['nextModule'])) {
                $path = $productPath;
                if ($module != Utilities::PRODUCT_MENU_NAME) {
                    $path .= '/modules/' . $module;
                }
                if ($module == $currentModule) {
                    $versionInfo['dependencies']['backend']  = $this->getBackendVersion($path);
                    $versionInfo['dependencies']['frontend'] = $this->getFrontendVersion($path, $versionInfo);
                } else {
                    $versionInfo['dependencies']['modules'][] = $this->getModulesVersion($path, $module);
                }
            }
        }        
        if(Utilities::getShowDbInVersionInfoParameter()) {
            $versionDb = $this->getVersionDB();
            $versionInfo['version'] .= ' ( DB Version - ' . $versionDb. ' )';
        }
        return $versionInfo;
    }

    protected function getVersionDB(){
        $nmObject = self::TEKNISA_ENTITIES ;
        $nrOrg = InstanceProvider::getEnvironment()->getCurrentOrganizationId();
        $customEntityManager = InstanceProvider::getConnectionCustom()->updateVpdConnection($nrOrg);
        $migration = MigrationRepository::getLastAppliedMigration($nmObject, $customEntityManager);
        if(empty($migration)){
            $version = '0';
        } else {
            $version = $migration[0]['NRVEROBJBD'];
        }
        return $version;
    }

    protected function getBackendVersion($path) {
        $version = array();
        $composerJsonFile = $this->getFileContentsDecoded($path . '/backend/composer.json');
        if($composerJsonFile) {
            $composerLockFile = $this->getFileContentsDecoded($path . '/backend/composer.lock');
            $requireKeys      = array_keys($composerJsonFile['require']);
            foreach ($composerLockFile['packages'] as $package) {
                if (in_array($package['name'], $requireKeys)) {
                    $versionEntities = $package['version'];
                    if($package['name'] == 'teknisa/entities'){
                        $versionDb = $this->getVersionDB();
                        $versionEntities = $versionEntities . ' ( ' . $versionDb . ' )';
                    }
                    array_push($version, array('name' => $package['name'], 'version' => $versionEntities));
                }
            }
        }
        return $version;
    }

    protected function getFrontendVersion($path, &$versionInfo) {
        $version = array();
        $bowerFile = $this->getFileContentsDecoded($path . '/mobile/bower.json');
        if($bowerFile) {
            $versionInfo['name'] = $bowerFile['name'];
            $versionInfo['version'] = isset($bowerFile['version']) ? $bowerFile['version'] : '';
            $requireKeys = array_keys($bowerFile['dependencies']);
            foreach ($requireKeys as $requireKey) {
                $depBowerFile = $this->getFileContentsDecoded($path . '/mobile/bower_components/' . $requireKey . '/bower.json');
                $depName    = $depBowerFile && isset($depBowerFile['name']) ? $depBowerFile['name'] : $requireKey;
                $depVersion = $depBowerFile && isset($depBowerFile['version']) ? $depBowerFile['version'] : "";
                array_push($version, array('name' => $depName, 'version' => $depVersion));
            }
        }
        return $version;
    }

    protected function getModulesVersion($path, $module) {
        $bowerFile = $this->getFileContentsDecoded($path . '/mobile/bower.json');
        $name      = $bowerFile && isset($bowerFile['name'])    ? $bowerFile['name']    : $module;
        $version   = $bowerFile && isset($bowerFile['version']) ? $bowerFile['version'] : "";
        return array( 'name' => $name, 'version' => $version );
    }

    protected function getFileContentsDecoded($filePath) {
        $fileContents = @file_get_contents($filePath);
        return $fileContents ? json_decode($fileContents, true) : null;
    }
} 