//
// Created by yukun on 27.11.19.
//
#include "Imagedisplay.hpp"
#include <fstream>
#include <iostream>

Imagedisplay::Imagedisplay() {
    offset = 0;
    width = 0;
    height = 0;
    bpp = 0;
}

Imagedisplay::Imagedisplay(const std::string &file) {
    offset = 0;
    width = 0;
    height = 0;
    bpp = 0;
    load(file);
}

void Imagedisplay::load(const std::string &file) {
    std::ifstream stream;
    stream.open(file);
    if(stream.is_open()){
        std::string str((std::istreambuf_iterator<char>(stream)),std::istreambuf_iterator<char>());
        data.resize(str.size());
        for(int i = 0; i < str.size();i++){
            data[i] = str[i];
        }
        offset = (int)*(unsigned int*)(&data[10]);
        width = (int)*(unsigned int*)(&data[18]);
        height = (int)*(unsigned int*)(&data[22]);
        bpp = (int)*(unsigned short*)(&data[28]);
    }
}

int Imagedisplay::getWidth() {
    return width;
}

int Imagedisplay::getHeight() {
    return height;
}

char *Imagedisplay::getData() {
    return &data[offset];
}

int Imagedisplay::getBitsPerPixel() {
    return bpp;
}

unsigned int Imagedisplay::getPixel(int x, int y) {
    unsigned int pixel = 0;
    char *ptr = getData() + ((getHeight() - 1 - y) * getWidth() + x) * (getBitsPerPixel() / 8);
    for(int i = 0; i < getBitsPerPixel() / 8;i++){
        *((char*)&pixel+i) = ptr[i];
       // std::cout<< "hi: im" << (unsigned int) ptr[i]<< std::endl;
    }
    if(pixel != 0){
        return pixel;
    }

    return pixel;
}
