use std::{path::PathBuf, str::FromStr};

use crate::{core, server::LspServer};
#[allow(unused)]
use log::info;
use tower_lsp::lsp_types::*;

use super::to_escape_path;

pub fn code_lens(
    #[allow(unused)]
    server: &LspServer,
    #[allow(unused)]
    params: &CodeLensParams
) -> Option<Vec<CodeLens>> {
    let hdl_param = server.srcs.hdl_param.clone();
    let uri = &params.text_document.uri;
    
    let path_to_hdl_file = hdl_param.path_to_hdl_file.read().unwrap();
    let pathbuf = PathBuf::from_str(uri.path()).unwrap();
    let pathbuf = to_escape_path(&pathbuf);
    let path_string = pathbuf.to_str().unwrap();

    let mut code_lens_array = Vec::<CodeLens>::new();
    if let Some(hdl_file) = path_to_hdl_file.get(path_string) {
        for module in &hdl_file.fast.content {
            code_lens_array.push(make_run_code_lens(path_string, module));
            code_lens_array.push(make_test_code_lens(path_string, module));
        }

        return Some(code_lens_array);
    }

    None
}

/// 快速仿真用的 按钮
fn make_test_code_lens(
    path_string: &str,
    module: &core::hdlparam::Module
) -> CodeLens {
    // 此处只有 name 和 path 有用
    let module_data_item: serde_json::Value = serde_json::json!({
        "icon": "",
        "name": module.name.to_string(),
        "type": "",
        "doFastFileType": "common",
        "range": null,
        "path": path_string.to_string(),
        "parent": null
    });
    let command = Command {
        title: "Test".to_string(),
        command: "digital-ide.tool.icarus.simulateFile".to_string(),
        arguments: Some(vec![module_data_item])
    };
    let code_lens = CodeLens {
        range: module.range.to_lsp_range(),
        command: Some(command),
        data: None
    };
    code_lens
}


/// netlist 用的按钮
fn make_run_code_lens(
    path_string: &str,
    module: &core::hdlparam::Module
) -> CodeLens {
    let file = serde_json::json!(path_string);
    let command = Command {
        title: "Run".to_string(),
        command: "digital-ide.netlist.show".to_string(),
        arguments: Some(vec![file])
    };
    let code_lens = CodeLens {
        range: module.range.to_lsp_range(),
        command: Some(command),
        data: None
    };
    code_lens
}