use crate::connections::db_connection;
use crate::models::{Couple, CoupleID, FamilyID, MemberID, NewCouple};
use crate::schema::couples;
use crate::services::photos_service;
use crate::utils::time_utils::time;
use diesel::prelude::*;

/// Create a new couple
pub async fn create(family_id: FamilyID) -> anyhow::Result<Couple> {
    db_connection::execute(|conn| {
        let res: Couple = diesel::insert_into(couples::table)
            .values(&NewCouple {
                family_id: family_id.0,
                time_create: time() as i64,
                time_update: time() as i64,
            })
            .get_result(conn)?;

        Ok(res)
    })
}

/// Get the information of a couple
pub async fn get_by_id(id: CoupleID) -> anyhow::Result<Couple> {
    db_connection::execute(|conn| couples::table.filter(couples::dsl::id.eq(id.0)).first(conn))
}

/// Get all the couples of a family
pub async fn get_all_of_family(id: FamilyID) -> anyhow::Result<Vec<Couple>> {
    db_connection::execute(|conn| {
        couples::table
            .filter(couples::dsl::family_id.eq(id.0))
            .get_results(conn)
    })
}

/// Get all the couples associated to a member
pub async fn get_all_of_member(id: MemberID) -> anyhow::Result<Vec<Couple>> {
    db_connection::execute(|conn| {
        couples::table
            .filter(
                couples::dsl::wife
                    .eq(id.0)
                    .or(couples::dsl::husband.eq(id.0)),
            )
            .get_results(conn)
    })
}

/// Check whether a couple with a given id exists or not
pub async fn exists(family_id: FamilyID, couple_id: CoupleID) -> anyhow::Result<bool> {
    db_connection::execute(|conn| {
        let count: i64 = couples::table
            .filter(
                couples::id
                    .eq(couple_id.0)
                    .and(couples::family_id.eq(family_id.0)),
            )
            .count()
            .get_result(conn)?;

        Ok(count != 0)
    })
}

/// Update the information of a couple
pub async fn update(couple: &mut Couple) -> anyhow::Result<()> {
    couple.time_update = time() as i64;

    db_connection::execute(|conn| {
        diesel::update(couples::dsl::couples.filter(couples::dsl::id.eq(couple.id().0)))
            .set((
                couples::dsl::state.eq(couple.state().map(|c| c.as_str().to_string())),
                couples::dsl::wife.eq(couple.wife().map(|m| m.0)),
                couples::dsl::husband.eq(couple.husband().map(|m| m.0)),
                couples::dsl::photo_id.eq(couple.photo_id().map(|p| p.0)),
                couples::dsl::time_update.eq(couple.time_update),
                couples::dsl::wedding_year.eq(couple.wedding_year),
                couples::dsl::wedding_month.eq(couple.wedding_month),
                couples::dsl::wedding_day.eq(couple.wedding_day),
                couples::dsl::divorce_year.eq(couple.divorce_year),
                couples::dsl::divorce_month.eq(couple.divorce_month),
                couples::dsl::divorce_day.eq(couple.divorce_day),
            ))
            .execute(conn)
    })?;

    Ok(())
}

/// Delete a couple photo
pub async fn remove_photo(couple: &mut Couple) -> anyhow::Result<()> {
    match couple.photo_id() {
        None => {}
        Some(photo) => {
            photos_service::delete(photo).await?;
            couple.set_photo_id(None);
            update(couple).await?;
        }
    }

    Ok(())
}

/// Delete a couple
pub async fn delete(couple: &mut Couple) -> anyhow::Result<()> {
    remove_photo(couple).await?;

    // Remove the couple
    db_connection::execute(|conn| {
        diesel::delete(couples::dsl::couples.filter(couples::dsl::id.eq(couple.id().0)))
            .execute(conn)
    })?;

    Ok(())
}

/// Delete all the couples of a family
pub async fn delete_all_family(family_id: FamilyID) -> anyhow::Result<()> {
    for mut m in get_all_of_family(family_id).await? {
        delete(&mut m).await?;
    }
    Ok(())
}
