using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.IDAL;

namespace Txgy.EWS.Client.DAL
{
    public class RemoteMySqlDownload : IRemoteMySqlDownload
    {
        public MySqlConnection RemoteConn { get; set; }
        public MySqlCommand Comm { get; set; }
        public MySqlDataAdapter Adap { get; set; }
        public MySqlDataReader DataReader { get; set; }
      
        /// <summary>
        /// 下载Json文件
        /// </summary>
        /// <param name="eventTime">事件时间</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="saveName">保存名称</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public int DownLoadJsonData(string eventTime, string savePath, string saveName, string tableName)
        {
            string courseSql = @"select JsonFile from " + tableName + " where EventTime=@eventTime";
          
            try
            {
                if (DBConnection())
                {
                    Comm = new MySqlCommand(courseSql, RemoteConn);
                    Comm.Parameters.AddWithValue("@eventTime", eventTime);
                    DataReader = Comm.ExecuteReader();

                    List<byte> jsonList = new List<byte>();
                    //开始读数据
                    while (DataReader.Read()) 
                    {
                        byte[] blob;
                        blob = (byte[])DataReader["JsonFile"];
                        if (blob.Length == 0)
                            break;
                        jsonList.AddRange(blob);
                    }

                    string jsonPath = savePath + saveName ;
                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    int len = SaveBinaryFile(jsonPath, jsonList.ToArray());
                    if (len == jsonList.Count)
                    {
                        return jsonList.Count;
                    }
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.Dispose();
            }
            return -1;
        }
        /// <summary>
        /// 下载波形文件
        /// </summary>
        /// <param name="eventTime">事件时间</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="saveName">保存名称</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public int DownLoadWavedata(string eventTime, string savePath, string saveName, string tableName)
        {
            string courseSql = @"select WaveData from " + tableName + " where EventTime=@eventTime";
            try
            {
                if (DBConnection())
                {
                    Comm = new MySqlCommand(courseSql, RemoteConn);
                    Comm.Parameters.AddWithValue("@eventTime", eventTime);
                    DataReader = Comm.ExecuteReader();

                    List<byte> wds = new List<byte>();
                    //开始读数据
                    while (DataReader.Read()) 
                    {
                        byte[] blob;
                        blob = (byte[])DataReader["wavedata"];
                        //Console.WriteLine(blob.Length);
                        if (blob.Length == 0)
                            break;
                        wds.AddRange(blob);
                    }
                    string mseedPath = savePath + saveName;
                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    int len = SaveBinaryFile(mseedPath, wds.ToArray());
                    if (len == wds.Count)
                    {
                        return wds.Count;
                    }
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.Dispose();
            }
            return -1;
        }
        /// <summary>
        /// 保存二级制文件
        /// </summary>
        /// <param name="fn"></param>
        /// <param name="datas"></param>
        /// <returns></returns>
        public int SaveBinaryFile(string fn, byte[] datas)
        {
            FileStream fs = new FileStream(fn, FileMode.OpenOrCreate);
            BinaryWriter binWriter = new BinaryWriter(fs);
            binWriter.Write(datas);
            binWriter.Close();
            fs.Close();
            return (int)new FileInfo(fn).Length;
        }
        private bool DBConnection()
        {
            string connStr = BusinessConfigManager.GetConnectionString("TencetnMySQL");
            if (RemoteConn == null)
                RemoteConn = new MySqlConnection(connStr);
            try
            {
                if (RemoteConn.State != ConnectionState.Open)
                {
                    RemoteConn.Open();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void Dispose()
        {
            if (Adap != null)
            {
                Adap.Dispose();
                Adap = null;
            }
            if (DataReader != null)
            {
                DataReader.Dispose();
                DataReader = null;
            }
            if (Comm != null)
            {
                Comm.Dispose();
                Comm = null;
            }
            if (RemoteConn != null)
            {
                RemoteConn.Close();
                RemoteConn.Dispose();
                RemoteConn = null;
            }
        }
    }
}
