<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace wendasns;

use think\App;
use think\Route;
use think\Service;
use wendasns\facade\Event;
use think\facade\Db;
use think\facade\Config;

class WendService extends Service
{
    public function boot(App $app)
    {
        $wdconfig = include root_path('vendor'.DIRECTORY_SEPARATOR.'wendasns'.DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'src').'config.php';
        Config::set($wdconfig, 'wendasns');
        
    	$appName = $app->http->getName();
    	if($appName=='admin'){
	        $this->registerRoutes(function (Route $route) {
	            $route->rule('<m>/<c>/<a>/<vars?>$', \wendasns\route\AdminDispatch::class);
	        });
    		return false;
    	}
    	if(in_array($appName,['addon'])){
    		return false;
    	}
    	$path = root_path('route').'app.php';
    	if(file_exists($path)){
    		include $path;
    	}
    	$this->registerRoutes(function(Route $route){
    		$this->wendRule($route);
    		$this->pluginRule($route);
        });
        Event::subscribe();
    }
    
    //插件路由设置
    private function pluginRule($route)
    {
		$dm = Db::name('application')->where('status',1)->select();
		foreach($dm as $v){
			$alias = $v['alias'];
			if(empty($v['domain'])){
				$route->group($alias, function()use($route, $alias){
					$route->rule('<c>/<a>$', \wendasns\route\InitDispatch::class)->append(['m'=>$alias,'model'=>'plugin']);
				});
			}else{//绑定域名
				$route->domain($v['domain'], function()use($route, $alias){
					$route->rule('<c>/<a>$', \wendasns\route\InitDispatch::class)->append(['m'=>$alias,'model'=>'plugin']);
				});
			}

			//插件自定义了路由
			$route_file = plugin_path($alias).'config'.DIRECTORY_SEPARATOR.'route.php';
			if(is_file($route_file)){
				$route_arr = include $route_file;
				$route->group($alias, function()use($route, $alias, $route_arr){
					foreach($route_arr as $key=>$val){
						list($controller, $action) = explode('/', $key);
						$route->rule($val, \wendasns\route\InitDispatch::class)->append(['m'=>$alias,'c'=>$controller,'a'=>$action,'model'=>'plugin'])->name("{$alias}/{$controller}/{$action}");
					}
				});
			}
		}
    }
    
    //路由数据表设置
    private function wendRule($route)
    {
    	$dm = Db::name('route')->where('status',1)->select();
    	foreach($dm as $v){
    		list($controller, $action) = explode('/',$v['controller']);
    		$route->rule($v['rule'], \wendasns\route\InitDispatch::class)->append(['m'=>$v['app'],'c'=>$controller,'a'=>$action,'model'=>'application'])->pattern(['id'=>'\d+','year'=>'\d+','month'=>'\d+','day'=>'\d+','kid'=>'.{11}','page'=>'\d+'])->name("{$v['app']}/{$controller}/{$action}");
    	}
    }
}
