# Copyright (C) 2007-2026 Ahmet Öztürk (aoz_2@yahoo.com)
#
# This file is part of Lifeograph.
#
# Lifeograph 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.
#
# Lifeograph 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 Lifeograph.  If not, see <http://www.gnu.org/licenses/>.

from LoG import *
import re

NAME="Format Dates to YYYY*MM*DD"
VERSION="0.1"
CATEGORY=SCtg.ENTRY_MODIFIER

# variables to be shared with the second call (run2):
name_opt = "Day/Month order"
option_default = "DAY/MONTH/YEAR"
entries = []

def run(entries_arg):
    global entries
    entries = entries_arg
    fields = [ { "type": FT.OPTION,
                 "name": name_opt, "opts": [option_default, "MONTH/DAY/YEAR"] } ]
    get_user_input( "Please specify Day/Month order in the existing dates", NAME, "run2", fields)

def run2(user_info : Dict[str, Any]):
    # captures D or DD, separator, M or MM, separator, YYYY:
    date_re = re.compile(r"\b(\d{1,2})[./](\d{1,2})[./](\d{4})\b")
    # day/month priority based on user input:
    do, mo = (1, 2) if user_info[name_opt] == option_default else (2, 1)

    # nested func to do the actual work:
    def format_dates(entry):
        for para in entry:
            text = para.get_text()
            for match in reversed(list(date_re.finditer(text))):
                d, m, year = match.group(do), match.group(mo), match.group(3)
                dt = Date.make(int(year), int(m), int(d))
                # if the preferred day/month order did not work, try the other one as a last resort:
                if not Date.is_valid(dt):
                    dt = Date.make(int(year), int(d), int(m))
                    if not Date.is_valid(dt):
                        continue
                new_text = Date.format_str(dt)
                start, end = match.start(), match.end()
                para.replace_text(start, end - start, new_text)

    for entry in entries:
        format_dates(entry)

    refresh_panels()
