#include "synapseMatrix.h"

SynapseMatrix::SynapseMatrix(){
    nbrLine = 0;
    nbrCol = 0;
}

SynapseMatrix::SynapseMatrix(unsigned int nbrL, unsigned int nbrC){
    nbrLine = nbrL;
    nbrCol = nbrC;
    createMatrix(nbrLine,nbrCol);
}

void SynapseMatrix::createMatrix(unsigned int line,unsigned int col){
    matrix = new Synapse*[line];
    for(unsigned int i=0 ; i<line; ++i){
        matrix[i] = new Synapse[col];
    }
}

unsigned int SynapseMatrix::getLineCount() const{
    return nbrLine;
}

unsigned int SynapseMatrix::getColumnCount() const{
    return nbrCol;
}

Synapse& SynapseMatrix::operator()(const unsigned int i,const unsigned int j) const throw(const unsigned int,std::string){
    if(nbrLine==0 || nbrCol==0)
        throw(std::string("Access on non initialized matrix"));
    if(i>(getLineCount()-1))
        throw(i);
    if(j>(getColumnCount()-1))
        throw(j);
    return matrix[i][j];
}

void SynapseMatrix::randomize(){
    //  cout << "            -> randomize " << this << endl;
    unsigned int nbrL = getLineCount();
    unsigned int nbrC = getColumnCount();
    srand(static_cast<unsigned>(time(0)));
    for(unsigned int i=0 ; i < nbrL ; ++i)
        for(unsigned int j=0 ; j < nbrC ; ++j){
            (*this)(i,j).setRandomWeight();
        }
}

void SynapseMatrix::deleteMatrix(){
    unsigned int nbrL = getLineCount();
    unsigned int nbrC = getColumnCount();
    if(nbrL&&nbrC){
        for(unsigned int i=0 ; i < nbrL ; ++i)
            delete[] matrix[i];
        delete[] matrix;
    }
}

SynapseMatrix::~SynapseMatrix(){
    deleteMatrix();
}

SynapseMatrix& SynapseMatrix::operator =(const SynapseMatrix& s){
    if(this!=&s){
        deleteMatrix();
        nbrLine = s.getLineCount();
        nbrCol = s.getColumnCount();
        createMatrix(nbrLine,nbrCol);
        for(unsigned int i=0 ; i < nbrLine ; ++i)
            for(unsigned int j=0 ; j < nbrCol ; ++j){
                (*this)(i,j) = s(i,j);
            }
    }
    return *this;
}

ostream & operator<<(ostream & os,const SynapseMatrix & mat){
    unsigned int nbrC = mat.getColumnCount();
    unsigned int nbrL = mat.getLineCount();
    for(unsigned int i=0 ; i < nbrL ; ++i){
        for(unsigned int j=0 ; j < nbrC ; ++j){
            os << setw(6) << mat(i,j) << " ";
        }
        os << endl;
    }
    return os;
}
