use crate::MEMORY_SIZE;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct EmulatorState {
    pub a: u8,
    pub b: u8,
    pub c: u8,
    pub d: u8,
    pub e: u8,
    pub h: u8,
    pub l: u8,

    pub cc: ConditionCodes,

    /// Stack pointer
    pub sp: u16,
    /// Memory pointer
    pub pc: u16,
    /// Enable interrupts
    pub ei: bool,
    /// Memory map
    pub memory: [u8; MEMORY_SIZE],
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ConditionCodes {
    /// Zero (Z), set if the result is zero.
    pub z: bool,
    /// Sign (S), set if the result is negative.
    pub s: bool,
    /// Parity (P), set if the number of 1 bits in the result is even.
    pub p: bool,
    /// Carry (C), set if the last addition operation resulted in a carry or if the last subtraction operation required a borrow.
    pub c: bool,
    // Auxiliary carry (AC or H), used for binary-coded decimal arithmetic (BCD).
    // Can't test this so I won't implement it
    // ac: bool,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Register {
    B,
    C,
    D,
    E,
    H,
    L,
    M,
    A,
    SP,
}

/// Returns a Register enum based on the input number 0..7 in the order B,C,D,E,H,L,M,A
pub fn register_from_num(b: u8) -> Register {
    match b {
        0 => Register::B,
        1 => Register::C,
        2 => Register::D,
        3 => Register::E,
        4 => Register::H,
        5 => Register::L,
        6 => Register::M,
        7 => Register::A,
        _ => panic!("'{b}' cannot be converted to register enum"),
    }
}

pub fn get_register(register: Register, state: &EmulatorState) -> u8 {
    match register {
        Register::B => state.b,
        Register::C => state.c,
        Register::D => state.d,
        Register::E => state.e,
        Register::H => state.h,
        Register::L => state.l,
        Register::A => state.a,
        Register::M => state.memory[u16::from_le_bytes([state.l, state.h]) as usize],
        Register::SP => unreachable!(),
    }
}

pub fn set_register(register: Register, value: u8, state: &mut EmulatorState) {
    match register {
        Register::B => state.b = value,
        Register::C => state.c = value,
        Register::D => state.d = value,
        Register::E => state.e = value,
        Register::H => state.h = value,
        Register::L => state.l = value,
        Register::A => state.a = value,
        Register::M => state.memory[u16::from_le_bytes([state.l, state.h]) as usize] = value,
        Register::SP => panic!("Cannot set 'SP' through set_register()"),
    };
}

pub fn get_register_pair(register: Register, state: &mut EmulatorState) -> u16 {
    match register {
        Register::B => u16::from_le_bytes([state.c, state.b]),
        Register::D => u16::from_le_bytes([state.e, state.d]),
        Register::H => u16::from_le_bytes([state.l, state.h]),
        Register::A => {
            // the PSW looks like this: SZ0A0P1C
            let flags: u8 = u8::from(state.cc.s) << 7 // bit 7
                | u8::from(state.cc.z) << 6 // bit 6
                //| u8::from(state.cc.a) << 4 // bit 4
                | u8::from(state.cc.p) << 2 // bit 2
                | 0x02 // bit 1
                | u8::from(state.cc.c); // bit 0

            u16::from_le_bytes([flags, state.a])
        }
        Register::SP => state.sp,
        _ => unreachable!(),
    }
}

pub fn set_register_pair(register: Register, value: u16, state: &mut EmulatorState) {
    let arr = value.to_le_bytes();
    let high = arr[1];
    let low = arr[0];
    match register {
        Register::B => {
            state.b = high;
            state.c = low;
        }
        Register::D => {
            state.d = high;
            state.e = low;
        }
        Register::H => {
            state.h = high;
            state.l = low;
        }
        Register::A => {
            state.a = high;
            // the PSW looks like this: SZ0A0P1C
            state.cc.s = low & 0b1000_0000 > 0;
            state.cc.z = low & 0b0100_0000 > 0;
            debug_assert!(low & 0b0010_0000 == 0, "malformed PSW");
            //state.cc.a = low & 0b0001_0000 > 0;
            debug_assert!(low & 0b0000_1000 == 0, "malformed PSW");
            state.cc.p = low & 0b0000_0100 > 0;
            debug_assert!(low & 0b0000_0010 > 0, "malformed PSW");
            state.cc.c = low & 0b0000_0001 > 0;
        }
        Register::SP => state.sp = value,
        _ => unreachable!(),
    }
}

/// Print values of registers and flags to stdout
pub fn print_state(state: &EmulatorState) {
    // State
    println!("\nsp\tpc\tei");
    println!("{:#06x}\t{:#06x}\t{}", state.sp, state.pc, state.ei);

    // Registers
    println!("\nB\tC\tD\tE\tH\tL\tA");
    println!(
        "{:#04x}\t{:#04x}\t{:#04x}\t{:#04x}\t{:#04x}\t{:#04x}\t{:#04x}",
        state.b, state.c, state.d, state.e, state.h, state.l, state.a
    );

    // Flags
    println!("\nz\ts\tp\tc");
    println!(
        "{}\t{}\t{}\t{}",
        state.cc.z, state.cc.s, state.cc.p, state.cc.c
    );
}
