use super::util::*;
use crate::schema::*;
use diesel::pg::*;
use diesel::prelude::*;
use rand::prelude::*;
use serde_json::{json, Serializer, Value};
use std::path::Path;
use std::time::*;
use uuid::Uuid;

pub fn db() -> PgConnection {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url))
}

// #[derive(Debug, Queryable, Identifiable, Insertable, serde::Serialize)]
// pub struct User {
//     pub id: i32,
//     pub username: String,
//     pub password: String,
//     pub salt: String,
//     pub image: String,
//     pub email: String,
//     pub google: String,
//     pub email_valid: String,
// }

// impl User {
//     pub fn create(username: String, email: String, pass_not_hashed: String) -> Result<Self, String> {
//         let mut rng = rand::thread_rng();
//         let y: f64 = rng.gen();
//         let salt = sha256::digest(y.to_string());

//         let pass_hashed = sha256::digest(format!("{}{}", &salt, &pass_not_hashed));
//         let uuid = Uuid::new_v4().to_string();
//         let result = diesel::insert_into(users::table)
//             .values((
//                 users::dsl::username.eq(username),
//                 users::dsl::password.eq(pass_hashed),
//                 users::dsl::salt.eq(salt),
//                 users::dsl::image.eq("/static/img/default_user.svg".to_string()),
//                 users::dsl::email_valid.eq(uuid),
//                 users::dsl::email.eq(email),
//                 users::dsl::google.eq("".to_string()),
//             ))
//             .get_result(&db());
//         if !result.is_err() {
//             let user_session = result.unwrap();
//             return Ok(user_session);
//         }
//         match result.err() {
//             Some(x) => {
//                 if format!("{}", x).contains("email") {
//                     return Err("Un compte est déjà associé à cet Email".to_string());
//                 } else if format!("{}", x).contains("username") {
//                     return Err("Ce nom d'utilisateur est déja utilisé".to_string());
//                 }
//                 return Err("Could not create user".to_string());
//             },
//             None => return Err("Could not create user".to_string())
//         }
//         Err("Could not create user".to_string())
//     }

//     pub fn find_all() -> Result<Vec<Self>, String> {
//         let result = users::dsl::users.get_results::<User>(&db());
//         if !result.is_err() {
//             let users = result.unwrap();
//             return Ok(users);
//         }
//         Err(format!("Users not found"))
//     }

//     pub fn find(id: i32) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::id.eq(id))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user_session = result.unwrap();
//             return Ok(user_session);
//         }
//         Err(format!("User {} not found", id))
//     }

//     pub fn update(self) -> Result<Self, String> {
//         let filter = users::dsl::users.filter(users::dsl::id.eq(self.id));
//         let result = diesel::update(filter)
//             .set((
//                 users::dsl::username.eq(self.username),
//                 users::dsl::password.eq(self.password),
//                 users::dsl::salt.eq(self.salt),
//                 users::dsl::image.eq(self.image),
//                 users::dsl::email.eq(self.email),
//                 users::dsl::email_valid.eq(self.email_valid),
//                 users::dsl::google.eq(self.google),
//             ))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user_session = result.unwrap();
//             return Ok(user_session);
//         }
//         Err(format!("User {} not update", self.id))
//     }

//     pub fn find_by_username(username: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::username.eq(&username))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User {} not find", &username))
//     }

//     pub fn find_by_changepass(changepass: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::password.eq(&changepass))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User {} not find", &changepass))
//     }

//     pub fn find_by_email(email: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::email.eq(&email))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User {} not find", &email))
//     }

//     pub fn find_by_key(key: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::username.eq(&key))
//             .filter(users::dsl::password.eq(""))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User {} not find", &key))
//     }

//     pub fn find_by_google(google: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::google.eq(&google))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User by google {} not find", &google))
//     }

//     pub fn find_by_email_valid(email_valid: &str) -> Result<Self, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::email_valid.eq(&email_valid))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User by email_valid {} not find", &email_valid))
//     }

//     pub fn generate_salt(&mut self) {
//         let mut rng = rand::thread_rng();
//         let y: f64 = rng.gen(); // generates a float between 0 and 1
//         self.salt = sha256::digest(y.to_string())
//     }

//     pub fn get_projects(&self) -> Result<Vec<Project>, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::creator_id.eq(&self.id))
//             .get_results::<Project>(&db());
//         if !result.is_err() {
//             let projects = result.unwrap();
//             return Ok(projects);
//         }
//         Err(format!("Project {} not fetched", self.id))
//     }

//     pub fn get_project_accesss(&self) -> Result<Vec<ProjectAccess>, String> {
//         let result = project_accesss::dsl::project_accesss
//             .filter(project_accesss::dsl::user_id.eq(&self.id))
//             .get_results::<ProjectAccess>(&db());
//         if !result.is_err() {
//             let project_accesss = result.unwrap();
//             return Ok(project_accesss);
//         }
//         Err(format!("ProjectAccesss {} not fetched", self.id))
//     }

//     pub fn delete(self) -> Result<String, String> {
//         let id = self.id.clone();
//         let name = self.username.clone();
//         let result_projects = self.get_projects();
//         let projects = result_projects.unwrap();
//         for project in projects {
//             project.delete();
//         }
//         let filter_user = users::dsl::users.filter(users::dsl::id.eq(&id));
//         let result_del_user = diesel::delete(filter_user)
//             .returning(users::dsl::username)
//             .get_result::<String>(&db());
//         if result_del_user.is_err() {
//             return Err(format!("User cannot be deleted in db()"));
//         }
//         return Ok("User was deleted".to_string());
//     }
// }

// #[derive(Debug, Queryable, Identifiable, Insertable, serde::Serialize)]
// pub struct Project {
//     pub id: i32,
//     pub creator_id: i32,
//     pub uuid: String,
//     pub name: String,
//     pub password: String,
//     pub time_limit: SystemTime,
//     pub premium: i32,
//     pub is_public: bool,
//     pub image: String,
//     pub origin_filename: String,
//     pub description: String,
//     pub data: String,
// }
// impl Project {
//     const FREE: i32 = 0;
//     const PAID: i32 = 1;

//     pub fn create(
//         name: String,
//         origin_filename: String,
//         password: String,
//         user: &User,
//     ) -> Result<Self, String> {
//         let result = diesel::insert_into(projects::table)
//             .values((
//                 projects::dsl::origin_filename.eq(origin_filename),
//                 projects::dsl::creator_id.eq(user.id),
//                 projects::dsl::uuid.eq(Uuid::new_v4().to_string()),
//                 projects::dsl::name.eq(name),
//                 projects::dsl::password.eq(password),
//                 projects::dsl::time_limit
//                     .eq(SystemTime::now() + Duration::new(60 * 60 * 24 * 5, 0)), // calcul pour 5 jour en seconde
//                 projects::dsl::premium.eq(Project::FREE),
//                 projects::dsl::is_public.eq(true),
//                 projects::dsl::description.eq("".to_string()),
//                 projects::dsl::data.eq("{}".to_string()),
//             ))
//             .get_result(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("Project not created"))
//     }

//     pub fn find(id: i32) -> Result<Self, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::id.eq(id))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("User {} not found", id))
//     }

//     pub fn find_by_uuid(uuid: &str) -> Result<Self, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::uuid.eq(&uuid))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("Project {} not find", &uuid))
//     }

//     pub fn find_by_public(is_public: bool) -> Result<Vec<Self>, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::is_public.eq(&is_public))
//             .get_results::<Project>(&db());
//         if !result.is_err() {
//             let projects = result.unwrap();
//             return Ok(projects);
//         }
//         Err(format!("User {} not found", &is_public))
//     }

//     pub fn update(self) -> Result<Self, String> {
//         let filter = projects::dsl::projects.filter(projects::dsl::id.eq(self.id));
//         let result = diesel::update(filter)
//             .set((
//                 projects::dsl::image.eq(self.image),
//                 projects::dsl::origin_filename.eq(self.origin_filename),
//                 projects::dsl::creator_id.eq(self.creator_id),
//                 projects::dsl::uuid.eq(self.uuid),
//                 projects::dsl::name.eq(self.name),
//                 projects::dsl::password.eq(self.password),
//                 projects::dsl::time_limit.eq(self.time_limit),
//                 projects::dsl::premium.eq(self.premium),
//                 projects::dsl::is_public.eq(self.is_public),
//                 projects::dsl::data.eq(self.data),
//                 projects::dsl::description.eq(self.description), 
//             ))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("Project {} not update", self.id))
//     }

//     pub fn get_entitys(&self) -> Result<Vec<Entity>, String> {
//         let result = entitys::dsl::entitys
//             .filter(entitys::dsl::project_id.eq(&self.id))
//             .get_results::<Entity>(&db());
//         if !result.is_err() {
//             let entitys = result.unwrap();
//             return Ok(entitys);
//         }
//         Err(format!("Project entitys {} not fetched", self.id))
//     }

//     pub fn get_creator(&self) -> Result<User, String> {
//         User::find(self.creator_id)
//     }

//     pub fn get_project_accesss(&self) -> Result<Vec<ProjectAccess>, String> {
//         let result = project_accesss::dsl::project_accesss
//             .filter(project_accesss::dsl::project_id.eq(&self.id))
//             .get_results::<ProjectAccess>(&db());
//         if !result.is_err() {
//             let project_accesss = result.unwrap();
//             return Ok(project_accesss);
//         }
//         Err(format!("ProjectAccesss {} not fetched", self.id))
//     }

//     pub fn delete(self) -> Result<String, String> {
//         let result_file = std::fs::remove_dir_all(Path::new("medias").join(self.uuid));
//         let filter_entity = entitys::dsl::entitys.filter(entitys::dsl::project_id.eq(&self.id));
//         let result_del_entity = diesel::delete(filter_entity)
//             .returning(entitys::dsl::name)
//             .get_results::<String>(&db());
//         if result_del_entity.is_err() {
//             return Err(format!("Project delete could not remove entity in db()"));
//         }
//         let filter_project = projects::dsl::projects.filter(projects::dsl::id.eq(&self.id));
//         let result_del_project = diesel::delete(filter_project)
//             .returning(projects::dsl::name)
//             .get_result::<String>(&db());
//         if result_del_project.is_err() {
//             return Err(format!("Project delete could not remove project in db()"));
//         }
//         return Ok("Project was deleted".to_string());
//     }

//     pub fn get_logs(&self) -> String {
//         let path = Path::new("./medias")
//             .join(self.uuid.clone())
//             .join("cmd_logs.txt");
//         if path.exists() {
//             return String::from_utf8_lossy(&std::fs::read(&path).unwrap()).to_string();
//         }
//         "".to_string()
//     }

//     const CONVERTION: i32 = 0;
//     const COMPLETE: i32 = 1;
//     const CRASHED: i32 = 2;

//     pub fn get_status(&self) -> i32 {
//         let path = Path::new("./medias")
//             .join(self.uuid.clone())
//             .join("cmd_logs.txt");
//         if path.exists() {
//             let metadata = std::fs::metadata(path).unwrap();
//             let modified_time = metadata.modified().unwrap().elapsed().unwrap().as_secs();
//             // println!("{} > 10", modified_time);
//             if modified_time > 300 {
//                 return Project::CRASHED;
//             }
//             return Project::CONVERTION;
//         }
//         Project::COMPLETE
//     }

//     pub const ACCESSREAD: i32 = 0;
//     pub const ACCESSWRITE: i32 = 1;

//     pub fn test_access(&self, result_user: &Result<User, String>, access_type: i32) -> bool {
//         if access_type == Project::ACCESSREAD && self.is_public {
//             return true;
//         } else if access_type == Project::ACCESSREAD && !result_user.is_err() {       
//             let user = result_user.as_ref().unwrap();
//             if user.id == self.creator_id {
//                 return true;
//             }
//             let result_pa = ProjectAccess::find(user.id,self.id);
//             if(!result_pa.is_err()){
//                 let pa = result_pa.unwrap();
//                 if(pa.access_type == Project::ACCESSREAD || pa.access_type == Project::ACCESSWRITE){
//                     return true;
//                 }
//             }
//         } else if access_type == Project::ACCESSWRITE && !result_user.is_err() {
//             let user = result_user.as_ref().unwrap();
//             if user.id == self.creator_id {
//                 return true;
//             }
//             let result_pa = ProjectAccess::find(user.id,self.id);
//             if(!result_pa.is_err()){
//                 let pa = result_pa.unwrap();
//                 if(pa.access_type == Project::ACCESSWRITE){
//                     return true;
//                 }
//             }
//         }
//         return false;
//     }

//     pub fn to_json(&self) -> Value {
//         let mut project_value = json!(self);
//         project_value["entitys"] = json!(self.get_entitys().unwrap());
//         project_value["creator"] = json!(self.get_creator().unwrap());
//         project_value["cmd_logs"] = json!(self.get_logs());
//         project_value["status"] = json!(self.get_status());
//         project_value["data"] = self.get_data();
//         let project_accesss = self.get_project_accesss().unwrap();
//         let mut project_accesss_json = Vec::new();
//         for project_access in project_accesss {
//             project_accesss_json.push(project_access.to_json());
//         }
//         project_value["project_accesss"] = json!(project_accesss_json);
//         project_value
//     }

//     pub fn duplicate(&self) -> Result<Self, String> {
//         let user = User::find(self.creator_id)?;
//         let mut project = Project::create(self.name.clone()+"_copy", self.origin_filename.clone(), self.password.clone(), &user)?;
//         project.description = self.description.clone();
//         project.is_public = self.is_public.clone();
//         project = project.update().unwrap();
//         let copy_result = copy_dir_all(Path::new("./medias").join(self.uuid.clone()), Path::new("./medias").join(project.uuid.clone()));
//         if copy_result.is_err() {
//             return Err(format!("You cannot copy {} in {}",self.uuid,project.uuid));
//         }
//         copy_result.unwrap();
//         let entitys = self.get_entitys()?;
//         for e in entitys {
//             let entity = e.duplicate(&project);
//         }
//         return Ok(project);
//     }

//     pub fn set_data(&mut self, object: &Value) {
//         self.data = object.to_string();
//     }

//     pub fn get_data(&self) -> Value {
//         serde_json::from_str(self.data.as_str()).unwrap()
//     }
// }

// #[derive(Debug, Queryable, Identifiable, Insertable, serde::Serialize)]
// pub struct Entity {
//     pub id: i32,
//     pub project_id: i32,
//     pub name: String,
//     pub type_entity: i32,
//     pub data: String,
//     pub parent_id: Option<i32>,
// }
// impl Entity {
//     pub const POTREE: i32 = 0;
//     pub const MODELE: i32 = 1;
//     pub const IMAGE360: i32 = 2;
//     pub const POTREEITEM: i32 = 3;
//     pub const GROUP: i32 = 3;

//     pub fn create(name: String, type_entity: i32, project: &Project) -> Result<Self, String> {
//         let result = diesel::insert_into(entitys::table)
//             .values((
//                 entitys::dsl::project_id.eq(project.id),
//                 entitys::dsl::name.eq(name),
//                 entitys::dsl::type_entity.eq(type_entity),
//                 entitys::dsl::data.eq(json!({}).to_string()),
//                 entitys::dsl::parent_id.eq(None::<i32>),
//             ))
//             .get_result(&db());
//         if !result.is_err() {
//             let entity = result.unwrap();
//             return Ok(entity);
//         }
//         Err(format!("Entity not created"))
//     }

//     pub fn duplicate(&self , project: &Project) -> Result<Self, String> {
//         let result = diesel::insert_into(entitys::table)
//             .values((
//                 entitys::dsl::project_id.eq(project.id),
//                 entitys::dsl::name.eq(self.name.clone()),
//                 entitys::dsl::type_entity.eq(self.type_entity),
//                 entitys::dsl::data.eq(self.data.clone()),
//                 entitys::dsl::parent_id.eq(None::<i32>),
//             ))
//             .get_result(&db());
//         if !result.is_err() {
//             let entity = result.unwrap();
//             return Ok(entity);
//         }
//         Err(format!("Entity not created"))
//     }

//     pub fn find(id: i32) -> Result<Self, String> {
//         let result = entitys::dsl::entitys
//             .filter(entitys::dsl::id.eq(id))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let entity = result.unwrap();
//             return Ok(entity);
//         }
//         Err(format!("User {} not found", id))
//     }

//     pub fn update(self) -> Result<Self, String> {
//         let filter = entitys::dsl::entitys.filter(entitys::dsl::id.eq(self.id));
//         let result = diesel::update(filter)
//             .set((
//                 entitys::dsl::project_id.eq(self.project_id),
//                 entitys::dsl::name.eq(self.name),
//                 entitys::dsl::type_entity.eq(self.type_entity),
//                 entitys::dsl::data.eq(self.data),
//                 entitys::dsl::parent_id.eq(self.parent_id),
//             ))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let entity = result.unwrap();
//             return Ok(entity);
//         }
//         Err(format!("Project {} not update", self.id))
//     }

//     pub fn set_data(&mut self, object: &Value) {
//         self.data = object.to_string();
//     }

//     pub fn get_data(&self) -> Value {
//         serde_json::from_str(self.data.as_str()).unwrap()
//     }

//     pub fn get_project(&self) -> Result<Project, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::id.eq(self.project_id))
//             .get_result::<Project>(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("User {} not found", self.project_id))
//     }

//     pub fn find_by_name_and_project(name: String, project_id: i32) -> Vec<Entity> {
//         let result = entitys::dsl::entitys
//             .filter(entitys::dsl::name.eq(&name))
//             .filter(entitys::dsl::project_id.eq(&project_id))
//             .get_results::<Entity>(&db());
//         if !result.is_err() {
//             let entitys = result.unwrap();
//             return entitys;
//         }
//         Vec::<Entity>::new()
//     }

//     pub fn delete(self) -> Result<String, String> {
//         let id = self.id.clone();
//         let name = self.name.clone();
//         let result_project = self.get_project();
//         if result_project.is_err() {
//             return Err(format!("Entity delete could not find project"));
//         }
//         let project = result_project.unwrap();
//         let entity_with_same_file = Entity::find_by_name_and_project(self.name, self.project_id);

//         if self.type_entity != Entity::POTREEITEM && entity_with_same_file.len() <= 1 {
//             let entity_path = Path::new("medias").join(project.uuid).join(&name);
//             if entity_path.exists() && entity_path.is_dir() {
//                 let result_file = std::fs::remove_dir_all(entity_path);
//                 if result_file.is_err() {
//                     return Err(format!("Entity delete could not remove folder"));
//                 }
//             } else if entity_path.exists() {
//                 let result_file = std::fs::remove_file(entity_path);
//                 if result_file.is_err() {
//                     return Err(format!("Entity delete could not remove file"));
//                 }
//             }
//         }

//         let filter_entity = entitys::dsl::entitys.filter(entitys::dsl::id.eq(&id));
//         let result_del_entity = diesel::delete(filter_entity)
//             .returning(entitys::dsl::name)
//             .get_result::<String>(&db());
//         if result_del_entity.is_err() {
//             return Err(format!("Entity delete could not remove project in db()"));
//         }
//         return Ok("Entity was deleted".to_string());
//     }
// }

// #[derive(Debug, Queryable, Identifiable, Insertable, serde::Serialize)]
// pub struct ProjectAccess {
//     pub id: i32,
//     pub user_id: i32,
//     pub project_id: i32,
//     pub access_type: i32,
// }
// impl ProjectAccess {

//     pub fn create(
//         user: &User,
//         project: &Project,
//         access: i32,
//     ) -> Result<Self, String> {
//         let project_access_result = ProjectAccess::find(user.id, project.id);
//         if !project_access_result.is_err(){
//             let mut project_access = project_access_result.unwrap();
//             project_access.access_type = access;
//             project_access = project_access.update().unwrap();
//             return Ok(project_access);
//         }
//         if ProjectAccess::find(user.id, project.id).is_err() {
//             let result = diesel::insert_into(project_accesss::table)
//             .values((
//                 project_accesss::dsl::user_id.eq(user.id),
//                 project_accesss::dsl::project_id.eq(project.id),
//                 project_accesss::dsl::access_type.eq(access),
//             ))
//             .get_result(&db());
//             let pa_project = project_accesss::dsl::project_accesss
//             .filter(project_accesss::dsl::project_id.eq(project.id))
//             .get_results::<ProjectAccess>(&db())
//             .unwrap();
//             if !result.is_err() {
//                 let project_access = result.unwrap();
//                 return Ok(project_access);
//             }
//         }
//         Err(format!("Project_Access not created"))
//     }

//     pub fn get_user(&self) -> Result<User, String> {
//         let result = users::dsl::users
//             .filter(users::dsl::id.eq(&self.user_id))
//             .get_result::<User>(&db());
//         if !result.is_err() {
//             let user = result.unwrap();
//             return Ok(user);
//         }
//         Err(format!("User {} not found", self.user_id))
//     }

//     pub fn get_project(&self) -> Result<Project, String> {
//         let result = projects::dsl::projects
//             .filter(projects::dsl::id.eq(&self.project_id))
//             .get_result::<Project>(&db());
//         if !result.is_err() {
//             let project = result.unwrap();
//             return Ok(project);
//         }
//         Err(format!("Project {} not found", self.project_id))
//     }

//     pub fn find(user_id: i32, project_id: i32) -> Result<Self, String> {
//         let result = project_accesss::dsl::project_accesss
//             .filter(project_accesss::dsl::user_id.eq(user_id))
//             .filter(project_accesss::dsl::project_id.eq(project_id))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project_access = result.unwrap();
//             return Ok(project_access);
//         }
//         Err(format!("Project Access with project_id{} and user_id{} not found", project_id, user_id))
//     }

//     pub fn find_id(id: i32) -> Result<Self, String> {
//         let result = project_accesss::dsl::project_accesss
//             .filter(project_accesss::dsl::id.eq(id))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project_access = result.unwrap();
//             return Ok(project_access);
//         }
//         Err(format!("ProjectAccess {} not found", id))
//     }

//     pub fn update(self) -> Result<Self, String> {
//         let filter = project_accesss::dsl::project_accesss.filter(project_accesss::dsl::id.eq(self.id));
//         let result = diesel::update(filter)
//             .set((
//                 project_accesss::dsl::user_id.eq(self.user_id),
//                 project_accesss::dsl::project_id.eq(self.project_id),
//                 project_accesss::dsl::access_type.eq(self.access_type),
//             ))
//             .get_result::<Self>(&db());
//         if !result.is_err() {
//             let project_access = result.unwrap();
//             return Ok(project_access);
//         }
//         Err(format!("ProjectAccess {} not update", self.id))
//     }

//     pub fn delete(self) -> Result<String, String> {
//         let id = self.id.clone();
//         let filter_pa = project_accesss::dsl::project_accesss.filter(project_accesss::dsl::id.eq(&id));
//         let result_del_pa = diesel::delete(filter_pa)
//             .returning(project_accesss::dsl::id)
//             .get_result::<i32>(&db());
//         if result_del_pa.is_err() {
//             return Err(format!("ProjectAccess cannot be deleted in db()"));
//         }
//         return Ok("ProjectAccess was deleted".to_string());
//     }

//     pub fn to_json(self) -> Value {
//         let mut project_access_value = json!(self);
//         project_access_value["user"] = json!(self.get_user().unwrap());
//         project_access_value["project"] = json!(self.get_project().unwrap());
//         project_access_value
//     }
// }