# encoding=utf-8
import random

from flask import request, g

from src.app.api.rooms import api
from src.app.api.rooms.validaters import RoomAddFrom, RoomListFrom, RoomDeleteFrom, RoomCreateTokenFrom
from src.libs.functions import result_format, GetRoomList, DeleteRoom, GetToken, CreateRoom, create_token
from src.libs.log_utils import Logger
from src.modules.room import Room


@api.route('/add', methods=['POST'])
def rome_add():
    """新建房间"""
    form = RoomAddFrom().validate_()
    token_list=[]
    user_ids=form.user_ids.data
    names=form.name.data
    RoomId = ''.join([str(random.randint(0, 999)).zfill(3) for _ in range(2)])
    if isinstance(user_ids,list):
        token = create_token(names,'')
        for name  in range(len(user_ids)):
               item = {}
               token = GetToken(names,user_ids[name])
               CreateRoom(token,user_ids[name],form.max_participants.data,form.empty_timeout.data,user_ids[name])
               # item['Name']=names
               item['RoomToken']=token
               item['UserId']=user_ids[name]
               token_list.append(item)
               form.name.data=user_ids[name]
               Room().set_attrs(form.data).direct_commit_()
    else:
        token = GetToken(names,user_ids)
        item = {}
        # item['Name'] = form.data.get('name')
        item['RoomToken'] = token
        item['UserId'] = user_ids
        token_list.append(item)
        CreateRoom(token,form.name.data,form.max_participants.data,form.empty_timeout.data,form.user_ids.data)
    return result_format(code=200,sign=token,data=token_list,roomid=RoomId,name=names)




@api.route('/gettoken', methods=['POST'])
def get_token():
    """生成token"""
    form = RoomCreateTokenFrom().validate_()
    token =GetToken(form.name.data,form.name.data)
    return result_format(code=200,token=token)

@api.route('/list', methods=['GET'])
def rome_list():
    """房间列表"""
    token=request.headers.get("Authorization")
    form = RoomListFrom(request.args).validate_()
    data=GetRoomList(token,form.names.data)
    return result_format(code=200, data=data)


@api.route('/delte', methods=['DELETE'])
def rome_delte():
    """删除房间"""
    token=request.headers.get("Authorization")
    form = RoomDeleteFrom().validate_()
    data=DeleteRoom(token,form.names.data)
    if data=={}:
       room_info = Room.query.filter(Room.name == form.names.data).first()
       if room_info:
           room_info.delete().stop_true()
    return result_format(code=200, data=data)
