#include "SpinInfo.h"
#include <algorithm>


int stringCheck(const std::string &stringToCheck)
{
    bool res = std::any_of(stringToCheck.begin(),stringToCheck.end(),
                   [&](char c) -> bool {
                   return (isdigit(c)||
                           c=='+'||
                           c=='-'||
                           c=='.'||
                           c=='\t'||
                           c=='e'
                           );});
    return (res ? 0 : -1);
}

SpinInfo SpinInfo::ParseJCouplingsAndGammas(std::vector<std::string> jCouplingsLines, std::vector<std::string> gammaLines)
{
    SpinInfo spinInfo;
    SamArray<char> parseBy;
    parseBy.push_back('\t');
    parseBy.push_back(' ');
    SamArray<double> buffer;
    buffer = ParseByCharacters<double>(jCouplingsLines[0],parseBy,0);
    long len = static_cast<long>(buffer.size());
    if(static_cast<long>(jCouplingsLines.size()) < len)
    {
        std::cout<<"Error: J-couplings provided do not represent a square matrix"<<std::endl;
        std::exit(2);
    }
    spinInfo.jCouplings.resize(len,len);
    spinInfo.gammas.resize(len,1);
    spinInfo.jCouplings. ZEROS;
    spinInfo.gammas. ZEROS;
    for(long i = 0; i < len; i++)
    {
        //function to delete newline character from windows files
        jCouplingsLines[i].erase(std::remove(jCouplingsLines[i].begin(), jCouplingsLines[i].end(), '\r'), jCouplingsLines[i].end());

        if(stringCheck(jCouplingsLines[i]) < 0)
        {
            throw std::runtime_error("Error in J-Coupling file: only 1,2,3,4,5,6,7,8,9,+,-,. and tabs are allowed as symbols in the file");
        }

        buffer = ParseByCharacters<double>(jCouplingsLines[i],parseBy,0);
        if(buffer.size() < len)
        {
            std::cout<<"Error: J-couplings provided do not represent a square matrix"<<std::endl;
            std::exit(3);
        }
        for(long j = 0; j < len; j++)
        {

            spinInfo.jCouplings.AT(i,j) = buffer[j];
        }
    }


    if(static_cast<long>(gammaLines.size()) < len)
    {
        std::cout<<"Error: gammas provided do not match the side length of the J-couplings matrix"<<std::endl;
        std::exit(3);
    }
    for(long i = 0; i < len; i++)
    {
        //function to delete newline character from windows files
        gammaLines[i].erase(std::remove(gammaLines[i].begin(), gammaLines[i].end(), '\r'), gammaLines[i].end());

        if(stringCheck(gammaLines[i]) < 0)
        {
            throw std::runtime_error("Error in Gamma file: only 1,2,3,4,5,6,7,8,9,+,-,. and tabs are allowed as symbols in the file");
        }

        spinInfo.gammas[i] = FromString<double>(gammaLines[i]);
    }
    return spinInfo;
}
