#include <algorithm>
#include <fstream>
#include <iostream>

#include "Catalog.h"

Catalog::Catalog()
{
    // Temporarily fill the catalog with some test data
#if 0
    m_catalog.push_back({"Target", "baranovich@gmail.com\nF-B-3-7"});
    m_catalog.push_back({"United", "david.sorber@gmail.com\nF-B-3-7"});
    m_catalog.push_back({"Pepco", "david.sorber@gmail.com\nNZ-98-O"});
    m_catalog.push_back({"Washington Gas", "baranovich@gmail.com\nS-N-718"});
#else
    const std::string pwFile("/home/dsorber/Documents/chicken_soup/chicken_soup.txt");

    std::ifstream infile(pwFile);
    if (! infile)
    {
        return;
    }

    // Iterate over the PW file and parse it (key is first line of each stanza
    // and the value are the remaining lines)
    std::string line;
    std::string key;
    std::string value;
    bool firstLine = true;
    while (std::getline(infile, line))
    {
        if (line.size() == 0)
        {
            // Debuggery
//            std::cout << "KEY: " << key << std::endl;
//            std::cout << "VAL: " << value << "\n" << std::endl;

            m_catalog.push_back({key, value});
            firstLine = true;
        }
        else
        {
            if (firstLine)
            {
                key.clear();
                value.clear();

                key.swap(line);
                firstLine = false;
            }
            else
            {
                value += line + "\n";
            }
        }
    }

    // Debuggery
//    std::cout << "KEY: " << key << std::endl;
//    std::cout << "VAL: " << value << "\n" << std::endl;
    m_catalog.push_back({key, value});

    // Close the input file
    infile.close();


#endif

    // Sort the catalog (A -> Z) for display purposes
    std::sort(
        m_catalog.begin(),
        m_catalog.end(),
        [](auto const& lhs, auto const& rhs)
        {
            return lhs.getLcKey() < rhs.getLcKey();
        });

}

Catalog::~Catalog()
{
}

void Catalog::setAllVisible()
{
    for (auto& item : m_catalog)
    {
        item.setVisibilty(true);
    }
}

void Catalog::filter(const std::string& criteria)
{
    // TODO: would be nice if there were a more efficient way to do this
    for (auto& item : m_catalog)
    {
        if (item.match(criteria))
        {
            item.setVisibilty(true);
        }
        else
        {
            item.setVisibilty(false);
        }
    }
}