using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace updateServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            NetManager manager = new NetManager();

            manager.start();


            UpdateManager.getInstance().init();
            ///ESPORTSTMNT06_1730991크로노
            //UpdateManager.getInstance().startUpdateEventRaw("ESPORTSTMNT02_1921265", false);


            //UpdateManager.getInstance().GameListUpdateWorker(true);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            UpdateManager.getInstance().startUpdateEventRaw(txbPlatformID.Text, false);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            UpdateManager.getInstance().GameListUpdateWorker(false);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            UpdateManager.getInstance().GameListUpdateWorker(true);
            //UpdateManager.getInstance().startUpdateEventRaw("ESPORTSTMNT06_1721059", false);
            //UpdateManager.getInstance().finishGameListUpdateWorker();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItems.Count < 1) return;

            string[] selectedItem = listBox1.SelectedItems[0].ToString().Split('_');

            txbGameID.Text = selectedItem.Last();
            txbPlatformID.Text = selectedItem[0] + "_" + selectedItem[1];

            UpdateManager.getInstance().GameKey = txbGameID.Text;
            UpdateManager.getInstance().GameName = txbPlatformID.Text;
        }

        public void removeWorkerList()
        {
            /*
            List<string> items = new List<string>();

            foreach (string s in UpdateManager.getInstance().mUpdateWorkerTable.Keys)
                items.Add(s);



            foreach (string s in items)
            {
                MessageBox.Show("!!" + s);
                UpdateManager.getInstance().mUpdateWorkerTable.Remove(s);
            }
            */
        }

        public void updateWorkerList()
        {
            this.Invoke(new MethodInvoker(() => {
                lstBoxUpdateGameList.Items.Clear();
                foreach (string item in UpdateManager.getInstance().mUpdateWorkerTable.Keys)
                {
                    lstBoxUpdateGameList.Items.Add(item);
                }
            }));
        }

        public void Msg()
        {
            //MessageBox.Show("!!");
        }

        public void updateGameRoomList(List<string> recvData)
        {
            this.Invoke(new MethodInvoker(() => {
                listBox1.Items.Clear();
                foreach (string item in recvData)
                {
                    listBox1.Items.Add(item);
                }
                
            }));
        }

        private void button5_Click(object sender, EventArgs e)
        {
            UpdateManager.getInstance().finishGameListUpdateWorker();
        }



        async void exportDB()
        {
            string basicfileName = DateTime.Now.Date.ToString("yyyyMMdd"); // initialize to the output file
            MongoClient dd = new MongoClient(DEFINE.몽고DB_접속정보);

            List<string> collectionNames = dd.GetDatabase("datalol").ListCollectionNames().ToList();


            int endedTask = 0;

            this.Invoke(new MethodInvoker(() => label4.Text = endedTask + "/" + collectionNames.Count().ToString()));

            DirectoryInfo di = new DirectoryInfo(@"c:\lol_db_backup\" + basicfileName);

            if (!di.Exists)
            {
                di.Create();
            }

            foreach (string item in collectionNames)
            {
                IMongoCollection<BsonDocument> collection = dd.GetDatabase("datalol").GetCollection<BsonDocument>(item); // initialize to the collection to read from

                using (var streamWriter = new StreamWriter(@"c:\lol_db_backup\" + basicfileName + @"\" + item + ".json"))
                {
                    await collection.Find(new BsonDocument())
                        .ForEachAsync(async (document) =>
                        {
                            using (var stringWriter = new StringWriter())
                            using (var jsonWriter = new JsonWriter(stringWriter))
                            {
                                var context = MongoDB.Bson.Serialization.BsonSerializationContext.CreateRoot(jsonWriter);
                                collection.DocumentSerializer.Serialize(context, document);
                                var line = stringWriter.ToString();
                                await streamWriter.WriteLineAsync(line);
                            }

                        }

                        
                        );


                    endedTask += 1;

                    this.Invoke(new MethodInvoker(() => label4.Text = endedTask + "/" + collectionNames.Count().ToString()));


                }
            }

        }

        async void importDB()
        {
            //MongoClient dd = new MongoClient(DEFINE.몽고DB_접속정보);
            MongoClient dd = new MongoClient("mongodb://root:veryhardpassword123@211.42.188.8:50003");
            List<string> collectionNames = dd.GetDatabase("datalol").ListCollectionNames().ToList();

            //List<string> collectionNames = new List<string>();

            //collectionNames.Remove("building_destroyed");
            //collectionNames.Add("game_end");
            //collectionNames.Add("game_info");

            string basicfileName = DateTime.Now.Date.ToString("yyyyMMdd");

            foreach (var item in collectionNames)
            {

                //IMongoCollection<BsonDocument> collection = dd.GetDatabase("data_lol_test_seed").GetCollection<BsonDocument>(item);
                IMongoCollection<BsonDocument> collection = dd.GetDatabase("datalol").GetCollection<BsonDocument>(item);

                using (var streamReader = new StreamReader(@"c:\lol_db_backup\" + basicfileName + @"\" + item + ".json"))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            await collection.InsertOneAsync(document);
                        }
                    }
                }

            }

        }

        async void clearDB()
        {

            MongoClient dd = new MongoClient(DEFINE.몽고DB_접속정보);

            List<string> collectionNames = dd.GetDatabase("datalol").ListCollectionNames().ToList();
            string basicfileName = DateTime.Now.Date.ToShortDateString();

            var mEventDataBaseTarget = dd.GetDatabase("datalol");
            foreach (string item in collectionNames)
            {
                await mEventDataBaseTarget.GetCollection<BsonValue>(item)
                   .DeleteManyAsync(x => true);
            }

            UpdateManager.getInstance().mUpdateWorkerTable.Clear();
            updateWorkerList();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            exportDB();
            //importDB();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            clearDB();
        }
    }
}
