// perm.cc      by Goro Takei      revised 6/18/98
// part of address book program

#include <stdlib.h>
#include "profile.h"
#include "list.h"
#include "compare.h"
#include <fstream.h>
#include "perm.h"

// This file contains the definition of function that does 
// not depend on how Profile is appended.  All necessary
// data members are already in the Class Profile and
// probably will not change.
// So, you may not need to compile this file again and again.


// "RewriteProfNum()" re-numbers the profile # in the 
// order listed.

void RewriteProfNum(List<Profile *> &list)
  {
    int i=1;
    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())    
      {
        if(LI.current()->GetProfNum()!=i)
         {
           LI.current()->EditProfNum(i);
         }
        i++; 
      }
  }


// "MakeFileOfLastNames" creates a file of last names only.
// The file is used to sort by last names using Unix command,
// sort().

void MakeFileOfLastNames(List<Profile *> list)
  {
    ofstream outfile("name.dat");
    outfile<<list.NumElts()<<endl;
    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())    
      {
        outfile<<LI.current()->GetLastName()<<endl;
      }
    outfile.close();
  }


// "SortNameFile()" uses Unix command, sort(), to sort
// last names of Profile stored in name.dat.
// The sorted list is stored in sname.dat to be read in
// by SortList().
//
// Note: sname.dat contains # of names listed at the top of
// the file (read as num_names)
//
// Note: this program can pick up more than one person with 
// same last name but it does NOT sort those people in the
// order of first name.

void SortNameFile()
  {                                    //sort command requires existing file
    ofstream outfile("sname.dat");     //so make sure that there exists a file
    outfile.close();                   //sname.dat.  If not, this makes it.
    cout<<endl<<"....sorting last names"<<endl;
    system("sort <name.dat> sname.dat");
  }

List<Profile *> SortList(List<Profile *> list)
  { 

    MakeFileOfLastNames(list);         //prepare name.dat
    SortNameFile();                    //prepare sname.dat

    List<Profile *> SortedList;
    ifstream in("sname.dat");
    char name[100];
    int num_names;
    char ** p;    //same as char* p[]
    p=new char* [num_names];            //p is a n-elemented vector of ptr to string

    in>>num_names;

    for(int i=0;i<num_names;i++) 
      {
        p[i]=new char[100];
        in.getline(p[i],100);       //read in the sname.dat file
      }
    in.close();

    cout<<endl<<"....sorting the list"<<endl;

    for(int i=0;i<num_names;i++)   //iterate through all names 
      {                            //for each name look for his profile
                                   //through all the list.
        CompareLastName Comp(p[i]);
 
        for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
          {
            if(Comp.Match(*LI.current())) 
              {
                SortedList.add(LI.current());  
              }  
           }
      }

    for(int i=0;i<num_names;i++) delete[] p[i];
    delete[] p;

    RewriteProfNum(SortedList);
    return SortedList;
  }

// "SearchList()" searches a list using one of exact match,
// wild card match and close match.

List<Profile *> SearchList(Compare &Comp, List<Profile *> list)   
  {
    List<Profile *> SearchResult;    
    int CMS=0;                   //flag for close match search     
    char ch;
    char LookString[100];
    strcpy(LookString,Comp.GetLookString());
    char LastChar=LookString[strlen(LookString)-1];
    char star='*';            // somehow, the "*" character is not recognized 
                              //by itself.  When I do name[i]=="*",
                              //I get pointer to int comparrison error.

    if(LastChar==star) 
      {                     //search for name field using ComprareName
//      cout<<"wild"<<endl;
        SearchResult=WildCardSearch(Comp,list);
      }
    else
      {
        cout<<"Would you like to find ones with close matches?(y,n) >"<<endl;
        cin>>ch; 
        cout<<"you entered "<<ch<<endl; 
        if((ch=='y')||(ch=='Y')) CMS=1;

//        cout<<"reg"<<endl; 
        SearchResult=Search(Comp,list);
//        cout<<"reg done"<<endl;
        ListIterator<Profile *> LI(SearchResult);
        if(!LI.more())
          {
            cout<<"....No match found"<<endl;
            cout<<"....close match enabled"<<endl;
            CMS=1;
          }
        if(CMS==1)
          {
//            cout<<"close"<<endl;
            SearchResult=CloseMatchSearch(Comp,list);
//            cout<<"close done"<<endl;
          }
      }
    return SearchResult;
  }



List<Profile *> Search(Compare &Comp, List<Profile *> list)
  {
    List<Profile *> NewList;
  	
    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
      {
                                       //the for-loop iterates through the list 
        if(Comp.Match(*LI.current()))    //Comp.Match checks if the profile of current
          {                             //pointer matches with the desired field in
//          LI.current().Display();     //CompareName, CompareStreet, etc.
            NewList.add(LI.current());  //creates new list that matches the condition
          }
      }
			
    return NewList;
  }

	


	
List<Profile *> WildCardSearch(Compare &Comp, List<Profile *> list)
  {
    List<Profile *> NewList;
  	
      for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
        {                               //the for-loop iterates through the list 
          if(Comp.WildCardMatch(*LI.current()))  	   //check for match
            { 
//            LI.current().Display();
              NewList.add(LI.current());    //creates new list that matches the condition
            }
        }
			
    return NewList;
  }

	

		
List<Profile *> CloseMatchSearch(Compare &Comp, List<Profile *> list)
  {
    List<Profile *> NewList;          

    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
      {     
                        //the for-loop iterates through the list 
        if(Comp.CloseMatch(*LI.current()))  //check for match
          {
//          LI.current().Display();
            NewList.add(LI.current());   //creates new list that matches the condition 
          }		
      }
			
    return NewList;
  }


	
	

// "DisplayList" shows all the profiles in the list.
// ".Display()" is a member function of class Profile.


void DisplayList(List<Profile *> &list)
  {
    cout<<endl;
    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
      { 
         LI.current()->Display();
      }
  }




//
// This "SaveList" is used when you add or remove Profile from the list, 
// since the line # will be changed after the added/removed profile.
//
// For ChangeProfile, rewriting the whole list is not needed because line #
// does not change.
//

void SaveList(List<Profile *> &list, char* ofname)	
  {
    ofstream out(ofname);
    out<<"Total Number of Profiles"<<endl;
    out<<list.NumElts()<<endl<<endl;
    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
      {
        LI.current()->Save(out);
      }
    out.close();
  }





// I pass WhoseProfile as an argument because I have to create
// ch outside the function and ch must know which field type
// will be changed.  In general, people will say
// I want to change "X data field of so_and_so's Profile" .
// So, I should know whose Profile I'm changing
// and how you want to be changed before I call this function.
// I didn't want to ask "which data field do you want to change?"
// before asking "Whose Profile do you want to change?"




// Unlike "ChangeList()", I get the name of the person to
// be removed inside the function because I don't need
// pre-proccessing (like creating Ch) for this funciton.

void RemoveProfile(List<Profile *> &list)
  {
    char flag[100];
    char WhoseProfile[100];

    cout<<"Enter the last name of person to delete profile >"<<endl;
    cin>>WhoseProfile;

    for(ListIterator<Profile *> LI(list);LI.more();LI.advance())
      {
        if(strcmp(LI.current()->GetLastName(),WhoseProfile)==0)
          {
            strcpy(flag,"");
            cout<<endl<<"Do you want to remove this profile?"<<endl;
            LI.current()->Display();
            while((strcmp(flag,"y")!=0)&&(strcmp(flag,"n")!=0))
              {
                cout<<"Enter y or n >"<<endl;
                cin>>flag;
                cout<<"you entered "<<flag<<endl;
              }
            if(strcmp(flag,"y")==0)
              {
                list.remove(LI.current());
                cout<<"profile removed:"<<endl;
              }
          }
      }
  RewriteProfNum(list);
  }
