/*
 * Copyright (c) 2022, Umut İnan Erdoğan <umutinanerdogan@pm.me>
 *
 * SPDX-License-Identifier: MPL-2.0
 */

#![allow(clippy::empty_loop)]

use core::sync::atomic::AtomicU64;

use crate::arch::memory::BootInfoFrameAllocator;
use crate::arch::{drivers::sysinfo::master, init, sloop};
use crate::devices::pci;
use crate::relib::network::socket::{SimpleSock, Socket};
use crate::{boot_conf::KernelConfig, scratchpad, systeminfo::RELEASE_TYPE};
// use crate::{boot_conf::KernelConfig, scratchpad, systeminfo::RELEASE_TYPE, TERM};
use crate::{filesystem, graphics_limine, hardware};
use kernel::KERNEL_VERSION;
use limine::LimineSmpInfo;
use limine::{LimineFramebufferRequest, LimineSmpRequest};

use spin::Lazy;

// FIXME: platform agnostic paging stuff
use x86_64::structures::paging::{Mapper, Size4KiB};

// TODO: Change this structure to allow for multiple cores loaded
pub static KERNEL_CONF: Lazy<KernelConfig> = Lazy::new(KernelConfig::new);
pub static FRAMEBUFFER: LimineFramebufferRequest = LimineFramebufferRequest::new(0);
pub static SMP: LimineSmpRequest = LimineSmpRequest::new(0);

/// The main entry point of the kernel
pub fn kernel_main(
    mut mapper: impl Mapper<Size4KiB>,
    mut frame_allocator: BootInfoFrameAllocator,
) -> ! {
    init::init();

    {
        // TODO: Setup config loaded from disk
        let mut kptr = KERNEL_CONF.as_mut_ptr();
        unsafe {
            *kptr = KernelConfig::new();
        }
    }
    if KERNEL_CONF.logging.enabled {
        log::set_max_level(KERNEL_CONF.log_level());
        // println!("{:#?}", *KERNEL_CONF);
    } else {
        log::set_max_level(log::LevelFilter::Off);
    }

    // let mut term = TERM.lock();
    // term.initialize();
    // term.set_dirty(true);
    // term.draw_term();
    // drop(term);

    pci::init(&mut mapper, &mut frame_allocator);

    x86_64::instructions::interrupts::without_interrupts(|| {
        hardware::init_mouse();
    });

    filesystem::init().unwrap();

    /*

    // println!("abc");
    let mut ipc_service = IPC.lock();
    // create some channels or whatever here then drop it
    let log_handle = ipc_service.create_channel("LOG", true);
    let log_sock_handle = ipc_service.create_socket("LOG", true);

    for handle in ipc_service.examine_board() {
        // println!("Discovered: {}", handle);
    }

    drop(ipc_service);


    */

    // use x86_ata::{init, ATA_BLOCK_SIZE};
    // 1. Initialise ATA Subsystem. (Perform Once, on boot)
    // init().expect("Failed To Start ATA...");
    // let mut buffer: [u8; ATA_BLOCK_SIZE] = [0; ATA_BLOCK_SIZE];
    // FIXME: Calls to read panic the kernel
    // read(0, 0, 0, &mut buffer);

    // for abc in list() {
    //     trace!("{:?}", abc);
    // }
    /*
    log_version_data();
    // */

    {
        // TODO: setup a proper framebuffer handler
        let fb_response = FRAMEBUFFER.get_response().get().unwrap();
        for fb in fb_response.framebuffers().unwrap() {
            trace!("Framebuffer {}x{}", fb.width, fb.height);
            trace!("{}", fb.memory_model);
            trace!("{}", fb.bpp);
            let mut count = 0;
            let total = fb.width * fb.height * 3;
            while count != total {
                unsafe {
                    let fb_ptr = fb.address.as_mut_ptr().unwrap();
                    *fb_ptr.offset((count).try_into().unwrap()) = 0xff;
                    *fb_ptr.offset((count + 1).try_into().unwrap()) = 0xff;
                    *fb_ptr.offset((count + 2).try_into().unwrap()) = 0xff;
                    *fb_ptr.offset((count + 3).try_into().unwrap()) = 0x00;

                    *fb_ptr.offset((count + 4).try_into().unwrap()) = 0x00;
                    *fb_ptr.offset((count + 5).try_into().unwrap()) = 0x00;
                    // *fb_ptr.offset((count + 6).try_into().unwrap()) = 0x00;
                }
                count += 6;
            }
        }
    }

    // // SMP
    // {
    //     let smp = SMP.get_response().get().unwrap();
    //     for cpu in smp.cpus().unwrap() {
    //         // unsafe {
    //         //     cpu.goto_address = *(trace_hcf as *const u64);
    //         // }
    //     }
    // }

    graphics_limine::clear_screen();

    scratchpad();
    sloop()
}

extern "C" fn trace_hcf(info: *const LimineSmpInfo) -> ! {
    trace!("CPU BOOT");
    loop {}
}

pub fn cpu_socket_startup() {
    let mut cpu_info_socket = SimpleSock::new();
    cpu_info_socket.register_protocol("CPU_INFO".to_string());

    // let x = master().unwrap();
    // let _xyz = x.brand_string().unwrap();
}

pub fn log_version_data() {
    info!("{} v{}", RELEASE_TYPE, KERNEL_VERSION);
    info!(
        "Brand String: {}",
        master().unwrap().brand_string().unwrap()
    );
}

pub static TICK: AtomicU64 = AtomicU64::new(0);

pub fn tick() {
    x86_64::instructions::interrupts::without_interrupts(|| {
        // let mut term = TERM.lock();

        // term.draw_term();
        use core::sync::atomic::Ordering::Relaxed;

        let mut data = TICK.load(Relaxed);
        data = data.wrapping_add(1);

        TICK.store(data, Relaxed);
    });
}
