// Generated by Qleany v1.4.8 from feature_controller.tera

use crate::FindAllDto;
use crate::FindAllResultDto;
use crate::FindResultDto;
use crate::FindTextDto;
use crate::ReplaceResultDto;
use crate::ReplaceTextDto;
use crate::units_of_work::find_all_uow::FindAllUnitOfWorkFactory;
use crate::units_of_work::find_text_uow::FindTextUnitOfWorkFactory;
use crate::units_of_work::replace_text_uow::ReplaceTextUnitOfWorkFactory;
use crate::use_cases::find_all_uc::FindAllUseCase;
use crate::use_cases::find_text_uc::FindTextUseCase;
use crate::use_cases::replace_text_uc::ReplaceTextUseCase;
use anyhow::Result;
use common::event::{Event, Origin};

use common::event::DocumentSearchEvent::FindAll;
use common::event::DocumentSearchEvent::FindText;
use common::event::DocumentSearchEvent::ReplaceText;

use common::undo_redo::UndoRedoManager;
use common::{database::db_context::DbContext, event::EventHub};
use std::sync::Arc;

pub fn find_text(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    dto: &FindTextDto,
) -> Result<FindResultDto> {
    let uow_context = FindTextUnitOfWorkFactory::new(db_context);
    let mut uc = FindTextUseCase::new(Box::new(uow_context));
    let return_dto = uc.execute(dto)?;
    // Notify that the handling manifest has been loaded
    event_hub.send_event(Event {
        origin: Origin::DocumentSearch(FindText),
        ids: vec![],
        data: None,
    });
    Ok(return_dto)
}

pub fn find_all(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    dto: &FindAllDto,
) -> Result<FindAllResultDto> {
    let uow_context = FindAllUnitOfWorkFactory::new(db_context);
    let mut uc = FindAllUseCase::new(Box::new(uow_context));
    let return_dto = uc.execute(dto)?;
    // Notify that the handling manifest has been loaded
    event_hub.send_event(Event {
        origin: Origin::DocumentSearch(FindAll),
        ids: vec![],
        data: None,
    });
    Ok(return_dto)
}

pub fn replace_text(
    db_context: &DbContext,
    event_hub: &Arc<EventHub>,
    undo_redo_manager: &mut UndoRedoManager,
    stack_id: Option<u64>,
    dto: &ReplaceTextDto,
) -> Result<ReplaceResultDto> {
    let uow_context = ReplaceTextUnitOfWorkFactory::new(db_context, event_hub);
    let mut uc = ReplaceTextUseCase::new(Box::new(uow_context));
    let return_dto = uc.execute(dto)?;
    undo_redo_manager.add_command_to_stack(Box::new(uc), stack_id)?;
    // Notify that the handling manifest has been loaded
    event_hub.send_event(Event {
        origin: Origin::DocumentSearch(ReplaceText),
        ids: vec![],
        data: None,
    });
    Ok(return_dto)
}
