use std::sync::Arc;

use cgmath::{Deg, Euler, Matrix4, Quaternion, Vector3};

use crate::input::InputState;
use crate::vulkan::{RendererDescriptorSets, TextureHandle};
use crate::vulkan::{MeshHandle, VulkanRenderer};

use super::pipelines::vs;

#[derive(Clone)]
pub struct GameObject {
    pub mesh_index: usize,
    pub texture_index: TextureHandle,
    pub normal_map_index: TextureHandle,
    pub position: Vector3<f32>,
    pub rotation: Quaternion<f32>,
    pub scale: Vector3<f32>,
    pub children: Vec<GameObject>,
    pub descriptor_sets: Vec<Arc<RendererDescriptorSets>>,
    pub is_selected: bool
}

impl GameObject {
    pub fn new(mesh: MeshHandle) -> GameObject {
        GameObject { mesh_index: mesh.index, texture_index: mesh.diffuse_handle, normal_map_index: mesh.normal_handle, position: Vector3::new(0.0, 0.0, 0.0),
            rotation: Quaternion::new(1.0, 0.0, 0.0, 0.0), scale: Vector3::new(1.0, 1.0, 1.0), children: vec![],
            descriptor_sets: vec![], is_selected: false }
    }

    pub fn _set_position(&mut self, x: f32, y: f32, z: f32) {
        self.position.x = x;
        self.position.y = y;
        self.position.z = z;
    }

    pub fn _set_scale(&mut self, x: f32, y: f32, z: f32) {
        self.scale.x = x;
        self.scale.y = y;
        self.scale.z = z;
    }

    pub fn _set_rotation(&mut self, euler_x: f32, euler_y: f32, euler_z: f32) {
        self.rotation = Quaternion::from(Euler::new(Deg(euler_x), Deg(euler_y), Deg(euler_z)));
    }

    pub fn _translate(&mut self, x: f32, y: f32, z: f32) {
        self.position.x += x;
        self.position.y += y;
        self.position.z += z;
    }

    pub fn _rotate(&mut self, x: f32, y: f32, z: f32) {
        self.rotation = self.rotation * Quaternion::from(Euler::new(Deg(x), Deg(y), Deg(z)));
    }

    pub fn get_push_constants(&self) -> vs::ty::PushConstants {
        vs::ty::PushConstants {
            model: self.get_model_matrix().into(),
            is_selected: if self.is_selected { 1 } else { 0 },
        }
    }

    pub fn get_model_matrix(&self) -> Matrix4<f32> {
        let translation = Matrix4::from_translation(self.position);
        let rotation: Matrix4<f32> = self.rotation.into();
        let scale = Matrix4::from_nonuniform_scale(self.scale.x, self.scale.y, self.scale.z);
        translation * rotation * scale
    }
}

#[derive(Debug, Clone, Copy)]
pub struct GameObjectHandle {
    pub object_index: usize
}

impl GameObjectHandle {
    pub fn get_game_object<'a>(&self, renderer: &'a VulkanRenderer) -> Option<&'a GameObject> {
        renderer.game_data.game_objects.get(self.object_index)
    }

    pub fn get_game_object_mut<'a>(&mut self, renderer: &'a mut VulkanRenderer) -> Option<&'a mut GameObject> {
        renderer.game_data.game_objects.get_mut(self.object_index)
    }
}

pub trait Updatable {
    fn update(&mut self, delta_time: f32, input: &InputState, renderer: &mut VulkanRenderer);
}
