# -*- coding: utf-8 -*-
"""
/***************************************************************************
 * 
 * Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
 * $Id$ 
 * 
 **************************************************************************/
 
 
 
/**
 * @file connectionmgr.py
 * @author daiwenkai(daiwenkai@baidu.com)
 * @date 2014/12/29 23:07:23
 * @version $Revision$ 
 * @brief 
 *  
 **/
"""

import logging
import random

import os
os.sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../")

import tools.configures.configmgr as configmgr
import tools.log as log
import globals.globals as globals

import libs.mcpack as mcpack

abs_path = os.path.dirname(os.path.abspath(__file__)) + "/../../"

conf = configmgr.ConfigMgr(globals.DEFAULT_GLOBAL_CONF_FILENAME)

class ConnectionMgr(object):
    """
    ConnectionMgr
    """
    log_filename = conf.log_file
    loger = log.init_log(log_filename)

    def __init__(self):
        """
        init ConnectionMgr
        """
        #self.header 请求头，类型不确定，与采用的协议强相关
        #self.body   请求内容，类型不确定，与采用的协议强相关
        self.conf = conf 
        # 连接相关的配置
        self.conn_group_num = conf.conn_group_num
        self.urls = conf.urls
        self.ports = conf.ports
        self.timeouts = conf.timeouts

    def set_conn_group(self):
        """
        选择conn_group中的ip与port，为建立连接做准备
        返回：三元组（ip, port, timeout）
        默认算法：随机
        """
        index = 2
        index = random.randint(0, self.conn_group_num - 1)
        res = (self.urls[index], 
                self.ports[index], 
                self.timeouts[index])
        logging.debug("[chosen conn: %s]" % (str(res)))
        return res

    def set_connection(self, conn):
        """
        set connection
        """
        self.conn = conn

    def set_header(self, header):
        """
        self.header进行赋值
        """
        self.header = header

    def set_body(self, body):
        """
        self.body进行赋值
        """
        self.body = body

    def prepare(self, headers, body):
        """
        prepare 设置header与body 
        """
        self.set_header(headers) 
        self.set_body(body)

    def connect(self, service, method, headers, body):
        """
        connect: 由具体协议类实现，不暴露给使用方
        """
        pass

    def process(self, service, method, params):
        """
        process: 由具体协议类实现，不暴露给使用方
        处理流程：prepare->connect->get_result
        """
        pass

    def get_response(self, service, method, params):
        """
        get response: 暴露给使用方
        """
        pass
    
"""
/* vim: set ts=4 sw=4 sts=4 tw=100 */
"""
