use std::borrow::Borrow;
use std::convert::TryFrom;

use actix_web::{delete, get, post, put, web, HttpResponse};
use serde::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};

use crate::db::errors::DatabaseError;
use crate::db::schedules::*;
use crate::db::tag::get_tag;
use crate::handlers::errors::ApiError;
use crate::return_models::ReturnSchedule;
use crate::types::EmgauwaUid;
use crate::utils::vec_has_error;

#[derive(Debug, Serialize, Deserialize)]
pub struct RequestSchedule {
	name: String,
	periods: Periods,
	tags: Vec<String>,
}

#[get("/api/v1/schedules")]
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let schedules = Schedule::get_all(&mut pool_conn).await?;

	let mut return_schedules: Vec<ReturnSchedule> =
		schedules.iter().map(ReturnSchedule::from).collect();
	for schedule in return_schedules.iter_mut() {
		schedule.load_tags(&mut pool_conn);
	}

	Ok(HttpResponse::Ok().json(return_schedules))
}

#[get("/api/v1/schedules/tag/{tag}")]
pub async fn tagged(
	pool: web::Data<Pool<Sqlite>>,
	path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let (tag,) = path.into_inner();
	let tag_db = get_tag(&mut pool_conn, &tag).await?;

	let schedules = Schedule::get_by_tag(&mut pool_conn, &tag_db).await?;

	let mut return_schedules: Vec<ReturnSchedule> =
		schedules.iter().map(ReturnSchedule::from).collect();
	for schedule in return_schedules.iter_mut() {
		schedule.load_tags(&mut pool_conn);
	}
	Ok(HttpResponse::Ok().json(return_schedules))
}

#[get("/api/v1/schedules/{schedule_id}")]
pub async fn show(
	pool: web::Data<Pool<Sqlite>>,
	path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let (schedule_uid,) = path.into_inner();
	let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;

	let schedule = Schedule::get_by_uid(&mut pool_conn, &emgauwa_uid).await?;

	let mut return_schedule = ReturnSchedule::from(schedule);
	return_schedule.load_tags(&mut pool_conn);
	Ok(HttpResponse::Ok().json(return_schedule))
}

#[post("/api/v1/schedules")]
pub async fn add(
	pool: web::Data<Pool<Sqlite>>,
	data: web::Json<RequestSchedule>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let new_schedule = Schedule::create(&mut pool_conn, &data.name, &data.periods).await?;

	new_schedule
		.set_tags(&mut pool_conn, data.tags.as_slice())
		.await?;

	let mut return_schedule = ReturnSchedule::from(new_schedule);
	return_schedule.load_tags(&mut pool_conn);
	Ok(HttpResponse::Created().json(return_schedule))
}

async fn add_list_single(
	conn: &mut PoolConnection<Sqlite>,
	request_schedule: &RequestSchedule,
) -> Result<Schedule, DatabaseError> {
	let new_schedule =
		Schedule::create(conn, &request_schedule.name, &request_schedule.periods).await?;

	new_schedule
		.set_tags(conn, request_schedule.tags.as_slice())
		.await?;

	Ok(new_schedule)
}

#[post("/api/v1/schedules/list")]
pub async fn add_list(
	pool: web::Data<Pool<Sqlite>>,
	data: web::Json<Vec<RequestSchedule>>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let result: Vec<Result<Schedule, DatabaseError>> = data
		.as_slice()
		.iter()
		.map(|request_schedule| {
			futures::executor::block_on(add_list_single(&mut pool_conn, request_schedule))
		})
		.collect();

	match vec_has_error(&result) {
		true => Ok(HttpResponse::from(
			result
				.into_iter()
				.find(|r| r.is_err())
				.unwrap()
				.unwrap_err(),
		)),
		false => {
			let mut return_schedules: Vec<ReturnSchedule> = result
				.iter()
				.map(|s| ReturnSchedule::from(s.as_ref().unwrap()))
				.collect();

			for schedule in return_schedules.iter_mut() {
				schedule.load_tags(&mut pool_conn);
			}
			Ok(HttpResponse::Created().json(return_schedules))
		}
	}
}

#[put("/api/v1/schedules/{schedule_id}")]
pub async fn update(
	pool: web::Data<Pool<Sqlite>>,
	path: web::Path<(String,)>,
	data: web::Json<RequestSchedule>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let (schedule_uid,) = path.into_inner();
	let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;

	let schedule = Schedule::get_by_uid(&mut pool_conn, &emgauwa_uid).await?;

	let schedule = schedule
		.update(&mut pool_conn, data.name.as_str(), data.periods.borrow())
		.await?;

	schedule
		.set_tags(&mut pool_conn, data.tags.as_slice())
		.await?;

	let mut return_schedule = ReturnSchedule::from(schedule);
	return_schedule.load_tags(&mut pool_conn);
	Ok(HttpResponse::Ok().json(return_schedule))
}

#[delete("/api/v1/schedules/{schedule_id}")]
pub async fn delete(
	pool: web::Data<Pool<Sqlite>>,
	path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
	let mut pool_conn = pool.acquire().await?;

	let (schedule_uid,) = path.into_inner();
	let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;

	match emgauwa_uid {
		EmgauwaUid::Off => Err(ApiError::ProtectedSchedule),
		EmgauwaUid::On => Err(ApiError::ProtectedSchedule),
		EmgauwaUid::Any(_) => {
			Schedule::delete_by_uid(&mut pool_conn, emgauwa_uid).await?;
			Ok(HttpResponse::Ok().json("schedule got deleted"))
		}
	}
}