import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { InoutsService } from '../inouts/inouts.service';
import * as JalaliMoment from 'moment-jalaali';
import * as moment from 'moment/moment';

@Injectable()
export class PanelsService {
  constructor(private prisma: PrismaService, private inout: InoutsService) {}

  async dashboard(user_id) {
    const Today = JalaliMoment(Date.now());
    const TodayMonth = Today.jMonth() + 1;
    const TodayYear = Today.jYear();
    const user = await this.prisma.userDetail.findFirst({
      where: { user_id },
      select: {
        vacation_remained: true,
      },
    });
    const today_inout = await this.prisma.inout.findMany({
      where: {
        user_id: user_id,
        time: {
          gte: new Date(new Date().setHours(0, 0, 0, 0)),
          lte: new Date(new Date().setHours(23, 59, 59, 999)),
        },
        delete: false,
      },
      select: {
        time: true,
      },
    });
    const getDuration = (first, second) => {
      const start = moment(first);
      const end = moment(second);
      const duration = end.diff(start, 'minutes');
      return duration;
    };
    let today_worked_minuets = 0;
    for (let i = 0; i < today_inout.length; i += 2) {
      const twoes = today_inout.slice(i, i + 2);
      today_worked_minuets += getDuration(
        twoes[0].time,
        twoes.length == 2 ? twoes[1].time : moment(),
      );
    }

    return await this.inout
      .findAll(user_id, TodayYear, TodayMonth, 'false')
      .then((r) => {
        delete r.items;
        return {
          ...r,
          today_inout:
            today_inout.length > 0 ? today_inout[today_inout.length - 1] : null,
          is_exit: today_inout.length % 2 === 0,
          today_worked_minuets: today_worked_minuets,
          vacation_remained: user.vacation_remained,
        };
      });
  }
}
