using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.Middlelayer.CncRepository.Repositories
{
    internal class SigerProjectMachineClockRepository : CncRepositoryBase<siger_project_machine_clock>, ISigerProjectMachineClock
    {
        private readonly ApiCncDbContext _context;
        public SigerProjectMachineClockRepository(ApiCncDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<ResponseToRecord> GetClockInData(List<int> ids, int projectId)
        {
            var query = from r in _context.siger_project_clock_record
                        join a in _context.siger_project_machine_attribution on r.machine_id equals a.machine
                        join e in _context.siger_project_machine on a.machine equals e.id
                        join l in _context.siger_project_level_section on a.station equals l.id
                        join lp in _context.siger_project_level_section on l.parentid equals lp.id
                        where r.projectid == projectId && r.status == (int)RowState.Valid && a.status == (int)RowState.Valid
                        && ids.Contains(r.id) && r.state==1
                        select new ResponseToRecord
                        {
                            machineCode = e.code,
                            machinesolution = $"{lp.title}-{l.title}",
                            clockin = r.starttime
                        };

            var temp= query.ToList();
            var now = UnixTimeHelper.GetNow();
            foreach (var item in temp)
            {
                var clockin = UnixTimeHelper.ConvertDataTimeLong(item.clockin);
                item.time = now - clockin;
            }
            return temp;
        }
    }
}
