// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2022Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Globalization;

namespace Hiperscan.GtkExtensions.Widgets
{
    public class OutLinedCalendarEntry : OutLinedEntry
    {
        public OutLinedCalendarEntry(Gtk.Entry entry) : base(entry)
        {
            this.SearchApplicationMainWindow(this.GtkEntry);
            this.EntryParentWindow.DeleteEvent += (o, args) => this.CloseCalenderWindow();
            this.EntryParentWindow.AddEvents((int)Gdk.EventMask.ButtonPressMask);
            this.EntryParentWindow.ButtonPressEvent += (o, args) => this.CloseCalenderWindow();

            this.GtkEntry.ButtonPressEvent += this.OnButtonPressed;
            this.GtkEntry.FocusOutEvent += (o, args) => this.CloseCalenderWindow();
            this.GtkEntry.Changed += this.OnGtkEntryTextChanged;
            this.GtkEntry.Activated += (sender, e) => this.CloseCalenderWindow();
        }

        [GLib.ConnectBefore]
        private void OnButtonPressed(object sender, Gtk.ButtonPressEventArgs e)
        {
            if (e.Event.Button != 1)
                return;

                if (this.IsCalenderShown == false)
            {
                this.IsCalenderShown = true;
                this.CreatePopupWindow();
            }
            else
            {
                this.IsCalenderShown = false;
                this.CloseCalenderWindow();
            }
        }

        private void CreatePopupWindow()
        {
            this.PopupWindow = new Gtk.Window(Gtk.WindowType.Popup);

            Gtk.VBox vbox = new Gtk.VBox();
            this.PopupWindow.Add(vbox);

            Gtk.Alignment alignment = new Gtk.Alignment(0.5f, 0.5f, 1.0f, 1.0f);
            alignment.SetPadding(5, 5, 5, 5);
            vbox.PackStart(alignment);
            this.Calendar = new Gtk.Calendar();
            alignment.Add(this.Calendar);

            alignment = new Gtk.Alignment(1.0f, 0.5f, 0.0f, 1.0f);
            alignment.SetPadding(5, 5, 5, 5);

            this.SetCalenderDate(true);
            this.Calendar.NextYear += this.OnYearChanged;
            this.Calendar.PrevYear += this.OnYearChanged;
            this.Calendar.PrevMonth += this.OnMonthChanged;
            this.Calendar.NextMonth += this.OnMonthChanged;
            this.Calendar.DaySelected += this.OnDayChanged;

            this.ShowCalendar();
        }

        private void ShowCalendar()
        {
            PopupPositioner.Show(this.PopupWindow, this.GtkEntry, true, 0, 5);
        }

        private void SetCalenderDate(bool initial)
        {
            if (this.IsCalenderShown == false)
                return;

            bool success = false;
            DateTime date;

            if (String.IsNullOrEmpty(this.ExactDateTimeFormat) == false)
                success = DateTime.TryParseExact(this.GtkEntry.Text, this.ExactDateTimeFormat, this.Culture, System.Globalization.DateTimeStyles.None, out date);
            else
                success = DateTime.TryParse(this.GtkEntry.Text, this.Culture, System.Globalization.DateTimeStyles.None, out date);


            if (success)
            {
                this.Calendar.Date = date;
            }
            else
            {
                if (initial)
                    this.Calendar.Date = this.DateTimeNow;
            }
        }

        public void CloseCalenderWindow()
        {
            if (this.PopupWindow != null)
            {
                this.PopupWindow.Destroy();
                this.PopupWindow = null;
                this.Calendar = null;
                this.IsCalenderShown = false;
                this.IsUpdating = false;
                this.IsDaySelected = true;
            }
        }

        private void SearchApplicationMainWindow(Gtk.Widget widget)
        {
            if (widget.Parent == null)
            {
                this.EntryParentWindow = widget as Gtk.Window;
                return;
            }

            this.SearchApplicationMainWindow(widget.Parent);
        }

        private void OnYearChanged(object sender, EventArgs e)
        {
            if (this.IsUpdating)
                return;

            this.IsUpdating = true;
            this.IsDaySelected = false;
            this.IsUpdating = false;
        }

        private void OnMonthChanged(object sender, EventArgs e)
        {
            if (this.IsUpdating)
                return;

            this.IsUpdating = true;
            this.IsDaySelected = false;
            this.IsUpdating = false;
        }

        private void OnDayChanged(object sender, EventArgs e)
        {
            if (this.IsUpdating)
                return;

            this.IsUpdating = true;

            if (this.IsDaySelected)
            {  
                this.GtkEntry.Text = this.Calendar.Date.ToString("d", this.Culture);
                this.CloseCalenderWindow();
            }
            else
            {
                if (String.IsNullOrEmpty(this.GtkEntry.Text) == false)
                    this.GtkEntry.Text = this.Calendar.Date.ToString("d", this.Culture);

                this.IsDaySelected = true;
            }

            this.IsUpdating = false;
        }

        private void OnGtkEntryTextChanged(object sender, EventArgs e)
        {
            if (this.IsUpdating)
                return;

            this.IsUpdating = true;
            this.SetCalenderDate(false);
            this.IsUpdating = false;
        }

        private new Gtk.Entry GtkEntry
        {
            get
            {
                return base.GtkEntry;
            }
        }

        private DateTime DateTimeNow
        {
            get
            {
                DateTime tmp = DateTime.Now;
                return new DateTime(tmp.Year, tmp.Month, tmp.Day);
            }
        }

        public CultureInfo Culture { get; set; } = CultureInfo.CurrentCulture;
        public string ExactDateTimeFormat { get; set; }

        private bool IsCalenderShown { get; set; } = false;
        private bool IsUpdating { get; set; }
        private bool IsDaySelected { get; set; } = true;

        private Gtk.Calendar Calendar { get; set; }
        private Gtk.Window PopupWindow { get; set; }
        private Gtk.Window EntryParentWindow { get; set; }
    }
}
