using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RTCP;
using RFramework;
using jiouosdptask.BLL;

namespace jiouosdptask.Tasks
{
    public class TcpManage
    {
        static TcpServerManage server = new TcpServerManage();
        public static void Start()
        {
            try
            {
                server.Error = ex => { Log.Write("接收失败:{0}", ex.Message); };
                server.Complete = inputBuffer =>
                {
                    string msg = server.Encoding.GetString(inputBuffer);
                    Log.Write("接到TCP命令:{0}", msg);
                    /*
                    接收格式:#jfxs#命令#数据#
                    返回格式:#jfxc#数据#
                    命令:
                     * 一元购开奖:yygkj
                     * 一元购计时:yygjs
                     */
                    if (string.IsNullOrEmpty(msg) != true)
                    {
                        string[] command = msg.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
                        if (command.Length == 3 && command[0] == "jfxs")
                        {
                            string txt = string.Empty;
                            string cmd = command[2];
                            switch (command[1])
                            {
                                case "yygkj":
                                    //cmd格式:开奖期数
                                    LotteryOpen.AddPeriodLotter(Guid.Parse(cmd.Trim()));
                                    txt = "200";
                                    break;
                                case "yygjs":
                                    //cmd格式:开奖期数
                                    txt = (LotteryOpen.GetPeriodLotter(Guid.Parse(cmd.Trim()))).ToString();
                                    break;
                                default: return server.Encoding.GetBytes("命令有错误101");
                            }

                            return server.Encoding.GetBytes(string.Format("#jfxc#{0}#", txt));
                        }
                        else
                        {
                            return server.Encoding.GetBytes("命令有错误102");
                        }
                    }
                    else
                    {
                        return server.Encoding.GetBytes("命令有错误103");
                    }
                };

                server.Start("127.0.0.1", 16561);
                Log.Write("TCP启动成功");
            }
            catch(Exception ex)
            {
                Log.Write("TCP启动失败:"+ex.Message);
            }
        }

        public static void Stop()
        {
            server.Stop();
        }
    }
}
