using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LolDataRequestLib.ResponseData
{
    internal class 한타딜량범위 : AResponseData
    {

        int 시작초 = 0;

        int 종료초 = 0;

        internal 한타딜량범위(int 받아온시작초, int 받아온종료초)
        {
            시작초 = 받아온시작초;
            종료초 = 받아온종료초;
        }

        protected override DataTable buildDataForResponse(BsonDocument recvDocument)
        {
            

           
            DataTable 한타딜량범위 = new DataTable();

            한타딜량범위.TableName = DBDefine.요청데이터분류.한타딜량범위.ToString();

            //선수관련

            한타딜량범위.Columns.Add("팀구분");
            한타딜량범위.Columns.Add("선수아이디");
            한타딜량범위.Columns.Add("챔피언");


            //데미지관련
            한타딜량범위.Columns.Add("데미지차이");
            한타딜량범위.Columns.Add("시작데미지량");
            한타딜량범위.Columns.Add("종료데미지량");
            한타딜량범위.Columns.Add("딜량백분율");



            if (m시작데이터.Count() == 0 || m종료데이터.Count() == 0)
            {
                return 한타딜량범위;
            }

            BsonArray 시작데이터선수리스트 = m시작데이터["participants"].AsBsonArray;

                foreach (BsonDocument itemPlayer in 시작데이터선수리스트)
                {

                DataRow bufRow = 한타딜량범위.NewRow();

                    
                    bufRow["팀구분"] = (DBDefine.팀구분)itemPlayer["teamID"].ToInt32();
                    bufRow["선수아이디"] = itemPlayer["playerName"].ToString();
                    bufRow["챔피언"] = itemPlayer["championName"].ToString();
                    bufRow["시작데미지량"] = itemPlayer["stats"].AsBsonArray.ToList().Where(v => v["name"] == "TOTAL_DAMAGE_DEALT_TO_CHAMPIONS").ToList()[0]["value"];

                한타딜량범위.Rows.Add(bufRow);

                }

            BsonArray 종료데이터선수리스트 = m종료데이터["participants"].AsBsonArray;

            foreach (BsonDocument itemPlayer in 종료데이터선수리스트)
            {
                DataRow bufPlayerRow = 한타딜량범위.AsEnumerable().Where(r => r.Field<String>("선수아이디") == itemPlayer["playerName"].ToString()).Last();

                bufPlayerRow["종료데미지량"] = itemPlayer["stats"].AsBsonArray.ToList().Where(v => v["name"] == "TOTAL_DAMAGE_DEALT_TO_CHAMPIONS").ToList()[0]["value"];
                bufPlayerRow["데미지차이"] = Convert.ToDouble(bufPlayerRow["종료데미지량"]) - Convert.ToDouble(bufPlayerRow["시작데미지량"]);
            }



            double 최대딜량 = Convert.ToDouble(한타딜량범위.AsEnumerable().OrderByDescending(r => Convert.ToDouble(r.Field<string>("데미지차이"))).First()["데미지차이"]);

            foreach (DataRow item in 한타딜량범위.Rows)
            {
                double 딜량차이값 = Convert.ToDouble(item["데미지차이"]);

                if (딜량차이값 != 0)
                {
                    item["딜량백분율"] = 딜량차이값 / 최대딜량 * 100.0;
                }
                else
                {
                    item["딜량백분율"] = 0.0;
                }
            }

            return 한타딜량범위;

        }

        BsonDocument m시작데이터 = new BsonDocument();

        BsonDocument m종료데이터 = new BsonDocument();

        protected override BsonDocument getDataFromMongo()
        {
           
                //var subfilter1 = Builders<BsonDocument>.Filter.Eq("RequestGameID", DataManager.getInstance().mPlatformGameID);

                var subFilter2 = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{'eventDocument.gameTime' : {$lt : " + 시작초  * 1000 + " }}");

            var filter1 = Builders<BsonDocument>.Filter.And(subFilter2); //var filter1 = Builders<BsonDocument>.Filter.And(subfilter1, subFilter2);

                var projectionFilter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{'eventDocument.participants' : 1 , 'eventDocument.gameTime' : 1 }");

                List<BsonDocument> documents = mEventDataBase.GetCollection<BsonDocument>("stats_update")
                    .Find(filter1)
                    .Project(projectionFilter)
                    .SortByDescending(x => x["sequenceIndex"])
                    .Limit(1)
                    .ToList();

            m시작데이터 = documents.Last()["eventDocument"].AsBsonDocument;

            subFilter2 = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{'eventDocument.gameTime' : {$lt : " + 종료초 * 1000 + " }}");

            filter1 = Builders<BsonDocument>.Filter.And(subFilter2); //filter1 = Builders<BsonDocument>.Filter.And(subfilter1, subFilter2);

            List<BsonDocument> documents2 = mEventDataBase.GetCollection<BsonDocument>("stats_update")
                    .Find(filter1)
                    .SortByDescending(x => x["sequenceIndex"])
                    .Project(projectionFilter)
                    .Limit(1)
                    .ToList();

            m종료데이터 = documents2.Last()["eventDocument"].AsBsonDocument;

            //구조를 위해 리턴은 하지만 이 상속클래스는 BsonDocument를 멤버변수 kv페어로 관리한다.
            return new BsonDocument();

        }
    }
}
