//! File and filesystem-related syscalls

use sbi_rt::legacy::console_getchar;
use crate::mm::page_table::translated_byte_buffer;
use crate::print;
use crate::task::manager::TASK_MANAGER;
use crate::task::processor::current_user_token;
use crate::task::suspend_current_and_run_next;

const FD_STDOUT: usize = 1;

// 从标准输入读取 指定长度的字符到 虚拟地址buffer中, 目前只支持长度为1
pub fn sys_read(fd: usize, buf: *const u8, len: usize) -> isize {
    match fd {
        FD_STDIN => {
            assert_eq!(len, 1, "Only support len = 1 in sys_read!");
            let mut c: usize;
            loop {
                // 利用sbi 从键盘获取输入的
                c = console_getchar();
                // 如果是0 说明还没有输入
                if c == 0 {
                    // 切换进程
                    suspend_current_and_run_next();
                    continue;
                } else {
                    break;
                }
            }
            // 把读取的字符 写入到应用的地址空间
            let ch = c as u8;
            // 由于目前长度只能为1, 这里直接获取第0个slice 写入
            let mut buffers = translated_byte_buffer(current_user_token(), buf, len);
            unsafe {
                buffers[0].as_mut_ptr().write_volatile(ch);
            }
            1
        }
        _ => {
            panic!("Unsupported fd in sys_read!");
        }
    }
}

/// write buf of length `len`  to a file with `fd`
pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
    match fd {
        FD_STDOUT => {
            // 根据当前页表 找到物理内存基地址
            // 这里需要从应用的地址空间里面寻找数据
            let buffers = translated_byte_buffer(current_user_token(), buf, len);
            for buffer in buffers {
                print!("{}", core::str::from_utf8(buffer).unwrap());
            }
            len as isize
        }
        _ => {
            panic!("Unsupported fd in sys_write!");
        }
    }
}
