<?php

namespace Server\websocket\web;

use App\Services\CloudService;
use Illuminate\Support\Facades\DB;
use Server\websocket\WebsocketService;

class IndexController extends WebsocketService {

    public function main(){
        global $_W;
        return $this->View(array(
            'title'=>"SOCKET配置",
            "setting"=>$this->settings,
            "userSign"=>$this->getKey("manager".$_W['uid'])
        ));
    }

    public function saveSet(){
        global $_W,$_GPC;
        if ($_W['ispost']){
            $data = $_GPC['data'];
            if (empty($data['server']) || empty($data['api'])) return $this->error("配置信息不完整");
            $data['type'] = trim($data['type']);
            if (!in_array($data['type'], array('remote', 'local'))){
                $data['type'] = 'remote';
            }
            if (!$this->SettingSave('swasocket', $data)){
                return $this->error("保存失败，请重试");
            }
            return $this->success("保存成功！",$this->url());
        }
        return $this->error("保存失败，请重试");
    }

    public function domain(){
        $basePath = $this->CheckInstall();
        $domainfile = $basePath."composer.json";
        if (is_error($basePath)) return $basePath;
        if (checksubmit()){
            global $_GPC;
            $data = $_GPC['domains'];
            $hosts = array();
            foreach ($data as $value){
                if (!empty($value)) $hosts[] = $value;
            }
            $writer = fopen($domainfile, 'w');
            if (!fwrite($writer, json_encode(array('host'=>$hosts)))){
                fclose($writer);
                return $this->error("保存失败，请重试");
            }
            fclose($writer);
            return $this->success("保存成功！",$this->url("domain"));
        }
        $domains = array("host"=>array());
        if (file_exists($domainfile)){
            $reader = fopen($domainfile,'r');
            $domaintext = fread($reader,filesize($domainfile));
            fclose($reader);
            if (!empty($domaintext)){
                $domains = @json_decode($domaintext, true);
            }
        }
        if (empty($domains['host'])){
            $domains['host'] = [$_SERVER['HTTP_HOST']];
        }
        return $this->View(array(
            "title"=>"SOCKET白名单",
            "hosts"=>$domains['host']
        ));
    }

    public function help(){
        $basePath = $this->CheckInstall();
        if (is_error($basePath)) return $basePath;
        return $this->View(array('title'=>"本地SOCKET安装步骤"));
    }

    public function CheckInstall(){
        return base_path('swasocket/');
        $basePath = base_path('swasocket/');
        if (!is_dir($basePath)){
            $zip = base_path('servers/websocket/webSocketGo.zip');
            if ($zip){
                $zipInstance = new \ZipArchive();
                $openRes = $zipInstance->open($zip);
                if ($openRes === TRUE) {
                    $zipInstance->extractTo(base_path('/'));
                    $zipInstance->close();
                    @unlink($zip);
                }else{
                    @unlink($zip);
                    return error(-1,__('unzipFailed'));
                }
                return $basePath;
            }
            $cloudRequire = CloudService::CloudRequire("laravel_whotalk_socket", $basePath);
            if (is_error($cloudRequire)) return $cloudRequire;
            DB::table('gxswa_cloud')->updateOrInsert(array(
                'identity'=>'laravel_whotalk_socket'
            ),array(
                'name'=>'WebSocket服务',
                'modulename'=>'',
                'type'=>3,
                'logo'=>$this->service['cover'],
                'website'=>$this->getEntry(),
                'rootpath'=>'swasocket/',
                'version'=>$this->service['version'],
                'online'=>'',
                'releasedate'=>$this->service['releases'],
                'addtime'=>TIMESTAMP,
                'dateline'=>TIMESTAMP
            ));
        }
        return $basePath;
    }

    public function makeEnv(){
        //初始化域名白名单
        global $_W;
        $host = parse_url($_W['siteroot']);
        $envs = array(
            "port"=>3001,
            "host"=>array($host['host']),    //域名白名单
            "notify_url"=>"",   //上线、下线、踢出通知地址
            "verify_url"=>""    //域名校验接口地址
        );
        $envFile = base_path("swasocket/env.json");
        if (file_exists($envFile)){
            $domainText = file_get_contents($envFile);
            if (!empty($domainText)){
                $envs = @json_decode($domainText, true);
            }
        }
        if (empty($domain)){
            $domain = $_SERVER['HTTP_HOST'];
        }
        if (!in_array($domain,$envs['host'])){
            $envs['host'][] = $domain;
            file_put_contents($envFile, json_encode($envs));
        }
    }

}
