extern crate image;
extern crate palette;


use image::{ImageBuffer};
use std::time::{Instant};
use std::io::{BufRead, BufReader};
use std::fs::File;
use palette::{Srgb, Shade, Pixel};

//We're cheating here. To do better, see https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
//https://stackoverflow.com/questions/35385703/read-file-character-by-character-in-rust


fn draw_dat_boi(target:u32) -> [u8;3]{

    let base = Srgb::new(0.62, 0.3, 0.3).into_linear();
    let lighter = base.lighten(0.04*target as f32);

    let pixel: [u8; 3] = Srgb::from_linear(lighter).into_format().into_raw();
    pixel
//    let colors:[[_; 3];10] = [[0,0,0],[255,0,0],[0,255,0],pixel,[255,255,0],[255,0,255],[0,255,255],[255, 165, 0],[127,127,127],[255,255,255]];
//    println!("{:?}", colors[target as usize]);
//    colors[target as usize]
}

fn main() {
    let now = Instant::now();
    let mut buff:image::RgbImage = ImageBuffer::new(1000,1001);

    let mut row = 0;
    let mut col = 0;

    let mut f = BufReader::new(File::open("pi.txt").expect("open failed"));

    let mut buf = Vec::<u8>::new();
    while f.read_until(b'\n', &mut buf).expect("read_until failed") != 0 {
        // this moves the ownership of the read data to s
        // there is no allocation
        let s = String::from_utf8(buf).expect("from_utf8 failed");


        for c in s.chars() {
            let color = draw_dat_boi(c.to_digit(10).unwrap());
            buff.put_pixel(col,row,image::Rgb(color));
            col += 1;
            if col > 999 { col=0; row += 1; };

        }
        // this returns the ownership of the read data to buf
        // there is no allocation
        buf = s.into_bytes();
        buf.clear();
        buff.save("pi.png").unwrap();
    };
    println!("{}", now.elapsed().as_secs());
}