using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using MercatorApi;
using MercatorExtensions;
using MercatorUi;
using MercatorDatabase;

// <CompileWithRoslyn />

namespace WorkTime
{
    public class Customizer : MercatorCommonCustomizers.WorkTimeCustomizer
    {
        public override OnUpdateRet OnUpdate(OnUpdateParam p)
        {
            // 1. Interdire le déplacement d'un pointage vers un autre jour
            if (IsDayChanged(p.Moment1Current, p.Moment1NewValue) || IsDayChanged(p.Moment2Current, p.Moment2NewValue))
            {
                return new OnUpdateRet
                {
                    DialogType = DialogTypeEnum.Stop,
                    Message = "Un pointage ne peut pas être déplacé vers un autre jour.",
                };
            }

            // 2. Demander confirmation si une heure est modifiée de plus de 2 heures
            if (IsChangedByMoreThan(p.Moment1Current, p.Moment1NewValue, TimeSpan.FromHours(2)) ||
                IsChangedByMoreThan(p.Moment2Current, p.Moment2NewValue, TimeSpan.FromHours(2)))
            {
                return new OnUpdateRet
                {
                    DialogType = DialogTypeEnum.AnswerYesNo,
                    Message = "Au moins une heure de pointage a été modifiée de plus de 2 heures. Voulez-vous confirmer cette modification ?",
                };
            }

            return new OnUpdateRet
            {
                DialogType = DialogTypeEnum._none,
            };
        }

        private static bool IsDayChanged(DateTime? current, DateTime? newValue)
        {
            return current.HasValue && newValue.HasValue && current.Value.Date != newValue.Value.Date;
        }

        private static bool IsChangedByMoreThan(DateTime? current, DateTime? newValue, TimeSpan tolerance)
        {
            return current.HasValue && newValue.HasValue && Math.Abs((newValue.Value - current.Value).TotalMinutes) > tolerance.TotalMinutes;
        }
    }
}