/*
 * textprocessor.cpp
 *
 *      Author: Simonas Saltenis
 */

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

using namespace std;

Textprocessor::TSortSearch::TSortSearch(istream& is)
{ is >> *this; }      // Use our overloaded operator>>

void Textprocessor::TSortSearch::sortlines(unsigned n)
{
	// in the comparison lambda, we also take care of cases when one or both of the strings are shorter than n
	// if not, we use string::compare (see its documentation).
	//
	sort(lines.begin(), lines.end(),
		 [n](const string& a, const string& b)
		    {return a.length() > n && b.length() > n ?
		    		a.compare(n, string::npos, b, n, string::npos) < 0 :
					(a.length() <= n && b.length() > n ? true : false);
		    });
}

void Textprocessor::TSortSearch::searchlines (unsigned n, const string& s, ostream& output) const
{
	for_each(lines.begin(), lines.end(),
			 [&](const string& a)
			 {if (a.length() > n && !a.compare(n, s.length(), s)) output << a << endl;} );
}

istream& Textprocessor::operator>>(istream& in, TSortSearch& ss)
{
	string s;
	ss.lines.clear();         // empty the lines vector
	while (getline(in,s))
		ss.lines.push_back(move(s));    // move(s) is an optimization, plain "s" is also OK but less efficient.
	return in;
}

ostream& Textprocessor::operator<<(ostream& out, const TSortSearch& ss)
{
    for (auto &s : ss.lines)
    	out << s << endl;
	return out;
}