# 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 *

NAME="Move under a Heading"
VERSION="0.1"
CATEGORY=SCtg.WORD_MODIFIER

def run(para, pos_bgn, pos_end):
    #check the heading level:
    if para.get_heading_level() != VT.PHS.NORMAL_TEXT:
        show_message("Headings cannot be moved!")
        return

    # get headings in the host entry:
    headings = []
    for p in para.get_host():
        heading_lvl = p.get_heading_level()
        if heading_lvl == VT.PHS.LARGE or heading_lvl == VT.PHS.MEDIUM:
            if p != _get_parent_heading(para): # omit current parent
                headings.append((p.get_text(), p.get_id()))

    fields = [ { "type": FT.OPTION, "name": "Heading", "opts": headings },
               { "type": FT.HIDDEN, "name": "Para",    "value": para.get_id() } ]
    # hidden field is used to pass the para-to-move to the input handler

    get_user_input( "Select the heading to move under", NAME, "handle_ret", fields)

# handle user input:
def handle_ret(user_info : Dict[str, Any]):
    diary = Diary.get_main()
    p_heading = diary.get_paragraph_by_id(user_info['Heading'])
    p_to_move = diary.get_paragraph_by_id(user_info['Para'])
    para_sub_last = _get_last_subpara(p_heading)

    # move:
    p_to_move.move_to_entry( p_heading.get_host(), para_sub_last)

    refresh_panels()

# calculate the insertion point:
def _get_last_subpara(p_heading: Paragraph):
    heading_lvl_last = heading_lvl_orig = p_heading.get_heading_level()
    para_sub_last = p_heading
    para_next = p_heading.get_next()
    while para_next:
        heading_lvl_next = para_next.get_heading_level()
        if heading_lvl_next > heading_lvl_last or heading_lvl_next == heading_lvl_orig:
            break
        para_sub_last = para_next
        heading_lvl_last = heading_lvl_next
        para_next = para_next.get_next()
    return para_sub_last

def _get_parent_heading(para: Paragraph):
    para_prev = para.get_prev()
    while para_prev:
        if para_prev.get_heading_level() > para.get_heading_level():
            return para_prev
        para_prev = para_prev.get_prev()
    return None

