using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper.ResultData;

namespace Siger.Middlelayer.Dapper
{
    public class DailySliceSateRepository : DapperRepositoryBase
    {
        public DailySliceSateRepository(int companyId, int projectId) : base(companyId, projectId)
        {
        }

        public async Task<IEnumerable<CncDailySliceSate>> GetCncDailySliceSatesAsync(IEnumerable<int> machineIds, DateTime sdate, DateTime edate)
        {
            //var start = UnixTimeHelper.GetUnixByShortDate(sdate.ToShortDateString());
            //var end = UnixTimeHelper.GetUnixByShortDate(edate.ToShortDateString());

            var search = "WHERE 1=1";
            //search += $" AND unix_timestamp(date) >= '{start}' AND unix_timestamp(date)<= '{end}'";

            search += $" AND date >= '{sdate}' AND date<= '{edate}'";

            if (machineIds != null && machineIds.Any())
            {
                search += $" AND machineID in ({string.Join(",", machineIds)})";
            }

            try
            {
                using (var conn = GetDbConnection())
                {
                    var executeQuery = $@"SELECT * FROM {CncDailySliceSate}
                                        {search} ORDER BY machineID, date";

                    return await conn.QueryAsync<CncDailySliceSate>(executeQuery);
                }
            }
            catch
            {
                throw;
            }
        }

        public IEnumerable<CncDailySliceSate> GetCncDailySliceSates(IEnumerable<int> machineIds, DateTime sdate, DateTime edate)
        {
            //var start = UnixTimeHelper.GetUnixByShortDate(sdate.ToShortDateString());
            //var end = UnixTimeHelper.GetUnixByShortDate(edate.ToShortDateString());

            var search = "WHERE 1=1";
            //search += $" AND unix_timestamp(date) >= '{start}' AND unix_timestamp(date)<= '{end}'";

            search += $" AND date >= '{sdate}' AND date<= '{edate}'";

            if (machineIds != null && machineIds.Any())
            {
                search += $" AND machineID in ({string.Join(",", machineIds)})";
            }
            try
            {
                using (var conn = GetDbConnection())
                {
                    var executeQuery = $@"SELECT * FROM {CncDailySliceSate}
                                        {search} ORDER BY machineID, date";

                    return conn.Query<CncDailySliceSate>(executeQuery);
                }
            }
            catch
            {
                throw;
            }
        }

        public override void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
