use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::vec::Vec;

#[derive(Debug, Clone)]
pub struct Graph {
    pub nodes: Vec<u32>,
    pub edges: Vec<(u32, u32)>,
}

#[derive(Debug)]
pub struct DirectedGraph {
    pub nodes: Vec<Vec<usize>>,
    pub explored: Vec<bool>,
    pub time: Vec<usize>,
    pub leader: Vec<usize>,
}

#[derive(Debug)]
pub struct DirectedWeightedGraph {
    pub nodes: Vec<Vec<(usize, usize)>>,
    pub distance: Vec<usize>,
}

pub fn read_to_vector(path: &str) -> Result<Vec<i64>, io::Error> {
    let file = File::open(path)?;
    let br = BufReader::new(file);
    let mut v = Vec::new();
    for line in br.lines() {
        let line = line?;
        let n = line
            .trim()
            .parse()
            .map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
        v.push(n);
    }
    Ok(v)
}

pub fn read_to_graph(path: &str) -> Result<Graph, io::Error> {
    let mut g = Graph {
        nodes: vec![],
        edges: vec![],
    };
    let file = File::open(path)?;
    let br = BufReader::new(file);

    for line in br.lines() {
        let line = line?;
        let mut nodes = line.split_whitespace();
        let current_node = nodes.next().unwrap().parse().unwrap();
        g.nodes.push(current_node);

        for neightbor in nodes {
            let neightbor: u32 = neightbor.parse().unwrap();
            // If the neighbor is smaller than the current node that means we
            // have already added it when we iterated over that smaller node.
            // Hence, we do not add the edge again.
            if neightbor > current_node {
                let edge = (current_node, neightbor);
                g.edges.push(edge);
            }
        }
    }
    Ok(g)
}

fn get_node_size(path: &str) -> Result<usize, io::Error> {
    let mut node_size = 0;
    let file = File::open(path)?;
    let br = BufReader::new(file);

    for line in br.lines() {
        let line = line?;
        let mut nodes = line.split_whitespace();
        let node: usize = nodes.next().unwrap().parse().unwrap();
        if node > node_size {
            node_size = node;
        }
    }
    Ok(node_size)
}

pub fn read_to_directed_graph(path: &str) -> Result<(DirectedGraph, DirectedGraph), io::Error> {
    let nodes: usize = get_node_size(path).unwrap();
    let mut g = DirectedGraph {
        nodes: vec![vec![]; nodes],
        explored: vec![false; nodes],
        time: vec![0; nodes],
        leader: vec![0; nodes],
    };

    let mut g_dash = DirectedGraph {
        nodes: vec![vec![]; nodes],
        explored: vec![false; nodes],
        time: vec![0; nodes],
        leader: vec![0; nodes],
    };

    let file = File::open(path)?;
    let br = BufReader::new(file);

    for line in br.lines() {
        let line = line?;
        let mut nodes = line.split_whitespace();
        let first_node: usize = nodes.next().unwrap().parse().unwrap();
        let second_node: usize = nodes.next().unwrap().parse().unwrap();

        g.nodes[first_node - 1].push(second_node - 1);
        g_dash.nodes[second_node - 1].push(first_node - 1);
    }

    Ok((g, g_dash))
}

pub fn read_to_directed_weighted_graph(path: &str) -> Result<DirectedWeightedGraph, io::Error> {
    let nodes: usize = get_node_size(path).unwrap();
    let mut g = DirectedWeightedGraph {
        nodes: vec![vec![]; nodes],
        distance: vec![1000000; nodes], // initial distance based on instructions
    };

    let file = File::open(path)?;
    let br = BufReader::new(file);

    for line in br.lines() {
        let line = line?;
        let mut nodes = line.split_whitespace();
        let current_node: usize = nodes.next().unwrap().parse().unwrap();

        for edge in nodes {
            let mut it = edge.split(",");
            let target_node: usize = it.next().unwrap().parse().unwrap();
            let distance: usize = it.next().unwrap().parse().unwrap();
            g.nodes[current_node - 1].push((target_node - 1, distance))
        }
    }
    Ok(g)
}
