/* diff_list_model.rs
 *
 * Copyright 2026 Christian Kruse
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use std::cell::{Cell, RefCell};

use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{gio, glib};

use crate::git::{DiffLineKind, DiffMode, FileDiff, WordRange};

#[derive(Debug, Clone)]
pub struct HunkInfo {
    pub hunk_index: usize,
    pub header: String,
    pub mode: DiffMode,
}

#[derive(Debug, Clone)]
pub struct DiffLineData {
    pub hunk_index: usize,
    pub line_index: usize,
    pub kind: DiffLineKind,
    pub old_lineno: Option<u32>,
    pub new_lineno: Option<u32>,
    pub content: String,
    pub word_ranges: Option<Vec<WordRange>>,
}

mod imp {
    use super::*;

    #[derive(Default)]
    pub struct DiffListModel {
        pub(super) items: RefCell<Vec<glib::BoxedAnyObject>>,
        pub(super) section_starts: RefCell<Vec<u32>>,
        pub(super) hunks: RefCell<Vec<HunkInfo>>,
        pub(super) is_new_file: Cell<bool>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for DiffListModel {
        const NAME: &'static str = "GitteDiffListModel";
        type Type = super::DiffListModel;
        type Interfaces = (gio::ListModel, gtk::SectionModel);
    }

    impl ObjectImpl for DiffListModel {}

    impl ListModelImpl for DiffListModel {
        fn item_type(&self) -> glib::Type {
            glib::BoxedAnyObject::static_type()
        }

        fn n_items(&self) -> u32 {
            self.items.borrow().len() as u32
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.items.borrow().get(position as usize).map(|o| o.clone().upcast())
        }
    }

    impl SectionModelImpl for DiffListModel {
        fn section(&self, position: u32) -> (u32, u32) {
            let n = self.items.borrow().len() as u32;
            if n == 0 {
                return (0, 0);
            }

            if self.is_new_file.get() {
                return (0, n);
            }

            let starts = self.section_starts.borrow();
            if starts.is_empty() {
                return (0, n);
            }

            let idx = match starts.binary_search(&position) {
                Ok(i) => i,
                Err(i) => i.saturating_sub(1),
            };

            let start = starts[idx];
            let end = starts.get(idx + 1).copied().unwrap_or(n);

            (start, end)
        }
    }
}

glib::wrapper! {
    pub struct DiffListModel(ObjectSubclass<imp::DiffListModel>)
        @implements gio::ListModel, gtk::SectionModel;
}

impl Default for DiffListModel {
    fn default() -> Self {
        Self::new()
    }
}

impl DiffListModel {
    pub fn new() -> Self {
        glib::Object::new()
    }

    pub fn set_diff(&self, diff: FileDiff, mode: DiffMode, is_new_file: bool) {
        let imp = self.imp();
        let old_n = imp.items.borrow().len() as u32;

        let mut items = Vec::new();
        let mut section_starts = Vec::new();
        let mut hunks = Vec::new();

        for (hunk_idx, hunk) in diff.hunks.into_iter().enumerate() {
            section_starts.push(items.len() as u32);
            hunks.push(HunkInfo {
                hunk_index: hunk_idx,
                header: hunk.header,
                mode,
            });

            for (line_idx, line) in hunk.lines.into_iter().enumerate() {
                items.push(glib::BoxedAnyObject::new(DiffLineData {
                    hunk_index: hunk_idx,
                    line_index: line_idx,
                    kind: line.kind,
                    old_lineno: line.old_lineno,
                    new_lineno: line.new_lineno,
                    content: line.content,
                    word_ranges: line.word_ranges,
                }));
            }
        }

        let new_n = items.len() as u32;

        // Store new data before emitting signals (GTK may call item() during emission)
        *imp.items.borrow_mut() = items;
        *imp.section_starts.borrow_mut() = section_starts;
        *imp.hunks.borrow_mut() = hunks;
        imp.is_new_file.set(is_new_file);

        self.items_changed(0, old_n, new_n);
        if !is_new_file && new_n > 0 {
            self.sections_changed(0, new_n);
        }
    }

    pub fn refresh_visible(&self) {
        let n = self.imp().items.borrow().len() as u32;

        if n > 0 {
            self.items_changed(0, n, n);
        }
    }

    pub fn clear(&self) {
        let imp = self.imp();
        let old_n = imp.items.borrow().len() as u32;

        imp.items.borrow_mut().clear();
        imp.section_starts.borrow_mut().clear();
        imp.hunks.borrow_mut().clear();
        imp.is_new_file.set(false);

        if old_n > 0 {
            self.items_changed(0, old_n, 0);
        }
    }

    pub fn hunk_info_for_position(&self, pos: u32) -> Option<HunkInfo> {
        let imp = self.imp();
        let starts = imp.section_starts.borrow();

        if starts.is_empty() {
            return None;
        }

        let idx = match starts.binary_search(&pos) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        };

        imp.hunks.borrow().get(idx).cloned()
    }

    pub fn is_new_file(&self) -> bool {
        self.imp().is_new_file.get()
    }

    pub fn n_items(&self) -> u32 {
        self.imp().items.borrow().len() as u32
    }

    pub fn line_data(&self, pos: u32) -> Option<DiffLineData> {
        let obj = self.item(pos)?;
        let boxed = obj.downcast_ref::<glib::BoxedAnyObject>()?;

        Some(boxed.borrow::<DiffLineData>().clone())
    }
}
