<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2016/10/15
 * Time: 下午3:52
 */

namespace search;

use Log;

abstract class tcp_client
{
    const time_out = 3600;
    const body_header_len = 10;

    //协议打包格式，PHP序列化用于PHP进程间通信，json 格式用于PHP与C++进程间通信
    const SerializeType = 1;
    const JsonType  = 2;
    private $mSocket;

    protected $mBodyType;

    protected function __construct()
    {
        $this->mSocket = false;
    }

    public function __destruct()
    {
        $this->fini_socket();
    }

    protected function request($param)
    {
        $times = 0;
        do
        {
            if($this->init_socket() == false) {
                return false;
            }

            $ret = $this->write_param($param);
            if($ret === false) {
                $this->fini_socket();
            }
        } while($ret == false && ++$times < 2);

        if($ret == true)
        {
            $body = $this->read_body();
            if($body != false)
            {
                if($this->mBodyType == tcp_client::SerializeType) {
                    return unserialize($body);
                } else {
                    return json_decode($body,true);
                }
            }
        }
        else
        {
            $this->fini_socket();
            return false;
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private function init_socket()
    {
        if($this->mSocket != false)
        {
            if(feof($this->mSocket) == true) {
                $this->fini_socket();
            } else {
                return true;
            }
        }

        $host = $this->remote_addr();
        $this->mSocket = stream_socket_client ($host,$err,$errno,30);
        if($this->mSocket == false) {
            Log::record("connect search server err --- code:{$errno} : {$err}");
            return false;
        } else {
            socket_set_timeout($this->mSocket,self::time_out);
            return true;
        }
    }

    private function fini_socket()
    {
        if($this->mSocket != false) {
            Log::record("tcp_client fini_socket",Log::DEBUG);
            stream_socket_shutdown($this->mSocket,STREAM_SHUT_RDWR);
            fclose($this->mSocket);
            $this->mSocket = false;
        }
    }

    private function read_body()
    {
        $body_len = $this->read(self::body_header_len);
        $body_len = intval($body_len);
        if($body_len > 0) {
            $body = $this->read($body_len);
            return $body;
        } else {
            return false;
        }
    }

    private function read($len)
    {
        $left = $len;
        $data = "";
        while ($left > 0)
        {
            if(feof($this->mSocket) == true) {
                return false;
            } else {
                $tmp = fread($this->mSocket,$left);
                $left = $left - strlen($tmp);
                $data .= $tmp;
            }
        }

        return $data;
    }
    private function write($data,$len)
    {
        while ($len > 0)
        {
            $ret = fwrite($this->mSocket,$data);
            if($ret == false || $ret <= 0) {
                return false;
            }
            else {
                $len -= $ret;
                $count = strlen($data);
                $data = substr($data,$ret,$count - $ret);
            }
        }

        return true;
    }

    private function write_param($param)
    {
        if($this->mBodyType == tcp_client::SerializeType) {
            $param = serialize($param);
        }
        else {
            $param = json_encode($param);
        }

        $len = sprintf("%010d",strlen($param));

        $data = $len . $param;
        return $this->write($data,strlen($data));
    }
    abstract function remote_addr();
}

class search_client extends tcp_client
{
    const GetRelatedWord = 1;
    const SearchReasult  = 2;
    const MatchPrice     = 3;
    const PromoteGoods   = 4;
    const ValidateArea   = 20;

    protected static $stInstance;
    public function __construct()
    {
        parent::__construct();
        $this->mBodyType = tcp_client::SerializeType;
    }
    public function __destruct()
    {
        parent::__destruct();
    }
    public static function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new search_client();
        }
        return self::$stInstance;
    }

    public function get_words($word)
    {
        $param = array("type" => self::GetRelatedWord, "keyword" => $word);
        return $this->request($param);
    }

    public function get_result($params)
    {
        $param = array("type" => self::SearchReasult, "params" => $params);
        return $this->request($param);
    }
    public function match_price($params)
    {
        $param = array("type" => self::MatchPrice, "params" => $params);
        return $this->request($param);
    }
    public function promote_goods($params)
    {
        $param = array("type" => self::PromoteGoods, "params" => $params);
        return $this->request($param);
    }

    public function get_area($area_id)
    {
        $param = array("type" => self::ValidateArea, "params" => array('area_id' => $area_id));
        return $this->request($param);
    }

    public function remote_addr()
    {
        global $config;

        $host = $config['searcher']['host'];
        $port = $config['searcher']['port'];

        return "{$host}:{$port}";
    }
}

class relation_client extends tcp_client
{
    const GetRelatedWord = 1;
    const SearchReasult  = 2;
    const MatchPrice     = 3;

    protected static $stInstance;
    public function __construct()
    {
        parent::__construct();
        $this->mBodyType = tcp_client::JsonType;
    }

    public static function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new relation_client();
        }
        return self::$stInstance;
    }
    public function __destruct()
    {
        parent::__destruct();
    }

    public function remote_addr()
    {
        global $config;

        $host = $config['relation']['host'];
        $port = $config['relation']['port'];

        return "{$host}:{$port}";
    }
    public function add_inviter($param)
    {
        $param = ["act" => 'inviter','op' => 'add', "params" => $param];
        $result = $this->request($param);
        if(empty($result)) return false;

        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return true;
        }
    }
    public function fetch_inviters($param)
    {
        $param = ["act" => 'inviter','op' => 'list', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['inviters'];
        }
    }
    public function fetch_invitees($param)
    {
        $param = ["act" => 'inviter','op' => 'invitees', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['invitees'];
        }
    }
    /////////////////////////////////////////////////////////////////////////
    public function add_follow($param)
    {
        $param = ["act" => 'follow','op' => 'add', "params" => $param];
        $result = $this->request($param);
        if(empty($result)) return false;

        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return true;
        }
    }
    public function del_follow($param)
    {
        $param = ["act" => 'follow','op' => 'del', "params" => $param];
        $result = $this->request($param);
        if(empty($result)) return false;

        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return true;
        }
    }
    public function fetch_follow($param)
    {
        $param = ["act" => 'follow','op' => 'fetch', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['follows'];
        }
    }
    public function add_special($param)
    {
        $param = ["act" => 'special','op' => 'add', "params" => $param];
        $result = $this->request($param);
        if(empty($result)) return false;

        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return true;
        }
    }
    public function del_special($param)
    {
        $param = ["act" => 'special','op' => 'del', "params" => $param];
        $result = $this->request($param);
        if(empty($result)) return false;

        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return true;
        }
    }

    public function fetch_self_special($param)
    {
        $param = ["act" => 'special','op' => 'fetch_self', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['specials'];
        }
    }

    public function fetch_pri_special($param)
    {
        $param = ["act" => 'special','op' => 'fetch_pri', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['specials'];
        }
    }
    public function fetch_pub_special($param)
    {
        $param = ["act" => 'special','op' => 'fetch_pub', "params" => $param];
        $result = $this->request($param);
        $code = intval($result['code']);
        if($code != 200) {
            return false;
        }
        else {
            return $result['data']['specials'];
        }
    }
}