#include "ftpro.h"
#include <windows.h>
#include <wx/utils.h>
#include <wx/dir.h>
#include <wx/textdlg.h>


BEGIN_EVENT_TABLE(LocalList,wxListCtrl)
  EVT_RIGHT_DOWN(LocalList::OnRightDown)

END_EVENT_TABLE()

void LocalList::OnRightDown(wxMouseEvent &event)
{

  MyPopupMenu menu("Local");
  menu.Append( ID_LOCAL_NEW_DIRECTORY_RC, "New Directory", "" );
  menu.Append( ID_LOCAL_NEW_FILE_RC, "New File", "" );
  menu.Append( ID_LOCAL_REMOVE_RC, "Remove", "" );
  menu.AppendSeparator();
  menu.Append( ID_LOCAL_PUT_RC, "Put ", "" );
  menu.AppendSeparator();
  menu.Append(ID_LOCAL_REFRESH_RC, "Refresh");
  menu.Append( ID_LOCAL_OPENR_RC, "Open", "" );
  menu.Append( ID_LOCAL_OPENP_RC,"Open in Programmer's Editor", "" );
  PopupMenu(&menu, event.GetX(),event.GetY());

}
void HarborDialog::OnLocalNewDir()
{
  wxString dir;
  dir = wxGetTextFromUser("What do you want to call the new directory?","Dir name","I_love_Charles");
  if (!(wxMkdir(dir)))
    {
      wxMessageDialog dialog(this, "Could not Make new Directory, aborting...",dir,wxOK);
      dialog.ShowModal();
    }
  GetLocalFiles(wxGetCwd());
  
}

void HarborDialog::OnLocalNewFile()
{
  wxString file;
  file = wxGetTextFromUser("What do you want to call the new file?","File name","I_love_Charles");
  if (file.empty())
    {
      wxMessageDialog dialog(this, "I cant make a file with no name stupid, im out","No File name",wxOK);
      dialog.ShowModal();
      return;
    }
  ofstream out(file.c_str());
  out << " ";
  out.close();
  GetLocalFiles(wxGetCwd());

}

void HarborDialog::OnLocalRemove()
{
  int sel, sel_type;
  wxString file;
  
  wxMessageDialog dialog(this, "Delete?","Warning: Deleteing ",wxYES_NO | wxICON_INFORMATION);
  if (dialog.ShowModal() == wxID_YES)
    {
      sel = GetSelected(HarborDialog::local_list);
      sel_type = HarborDialog::local_list->GetItemData(sel);
      file = HarborDialog::local_list->GetItemText(sel);
      if (sel_type == 0)
        {
          if (!(RemoveDirectory(file)))
            {
              wxMessageDialog dialog(this, "Could not delete directory, it must be empty first","Error: Deleting",wxOK | wxICON_ERROR);
              dialog.ShowModal();
              return;
            }
        }
      else
        {
          wxRemoveFile(file);
          if (wxFileExists(file))
            {
              wxMessageDialog dialog(this, "Error in removing file","Error: Deleting",wxOK | wxICON_ERROR);
              dialog.ShowModal();
              return;
            }
        }
    }
  HarborDialog::local_list->DeleteItem(sel);
}



void HarborDialog::OnLocalPut()
{
  unsigned short int sel;
  wxString selected;
  wxBeginBusyCursor();
  sel = GetSelected(HarborDialog::local_list);
  selected = HarborDialog::local_list->GetItemText(sel);
  wxProgressDialog PU("Uploading...Please wait","Uploading");
  if (!(GetFTP().PutFile(selected.c_str(), PU)))
    {
      wxMessageDialog dialog(this, "Error in uploading, do you have the right permissions ?","Error in uploadin",wxOK);
      dialog.ShowModal();
      return;
    }
  GetRemoteFiles();
  wxEndBusyCursor();
}

void HarborDialog::OnLocalRegularOpen()
{
  unsigned short int sel;
  wxString selected;
  
  if (HarborDialog::local_list->GetSelectedItemCount() == 0)
    {
      wxMessageDialog dialog(this, "You must select an Item to Open","Error: None Selected",wxOK | wxICON_ERROR);
      dialog.ShowModal();
      return;
    }
  sel = GetSelected(HarborDialog::local_list);
  
  selected = HarborDialog::local_list->GetItemText(sel);
  
  if (!(selected.IsEmpty()))
    {
      wxString temp = GetRegularEditor() + " \"" + wxGetCwd() + "\\" + selected + "\"";
      if (!(wxExecute(temp)))
        {
          wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", GetRegularEditor(), wxOK | wxICON_ERROR);
          dialog.ShowModal();
        }
    }
  
}

void HarborDialog::OnLocalProgrammerOpen()
{

  unsigned short int sel;
  wxString selected;
  
  if (HarborDialog::local_list->GetSelectedItemCount() == 0)
    {
      wxMessageDialog dialog(this, "You must select an Item to Open","Error: None Selected",wxOK | wxICON_ERROR);
      dialog.ShowModal();
          return;
    }
  sel = GetSelected(HarborDialog::local_list);
  
  selected = HarborDialog::local_list->GetItemText(sel);
  
  if (!(selected.IsEmpty()))
    {
      wxString temp = GetProgrammingEditor() + " \"" + wxGetCwd() + "\\" + selected + "\"";
      if (!(wxExecute(temp)))
        {
          wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", GetRegularEditor(), wxOK | wxICON_ERROR);
          dialog.ShowModal();
        }
    }
  
}


void HarborDialog::OnLocalCdup( wxCommandEvent &event )
{
  if (wxGetCwd().IsSameAs("C:\\"))
    {
      wxMessageDialog dialog(this, "Your already at the top level","Error: Top Level",wxOK);
      dialog.ShowModal();
      return;
    }
  
  if (!(wxSetWorkingDirectory("..")))
    {
      wxMessageDialog dialog(this, "Couldn't go up any further!","Error: Directory error",wxOK);
      dialog.ShowModal();
    }
  
  GetLocalFiles(wxGetCwd());
}  


void HarborDialog::OnLocalHome( wxCommandEvent &event )
{
  if (!(wxSetWorkingDirectory(GetHome())))
    {
      wxMessageDialog dialog(this, "Your home directory is invalid\nYou can change it in Settings->SetHome",GetHome(),wxOK);
      dialog.ShowModal();
      return;
    }
  GetLocalFiles(wxGetCwd());

}


void HarborDialog::OnLocalPWDTextChange()
{
  //this is nigger shit, but it has to be done, i cant get the value when they hit enter, for some reason

  wxString temp = local_pwd_cb->GetValue();
  if (!(temp.IsEmpty()))
    {
      if (temp[temp.Length() - 1] == '\\')
        {
          if (!(wxSetWorkingDirectory(local_pwd_cb->GetValue())))
            {
              wxMessageDialog dialog(this, "Cant change to that directory,...aborting",local_pwd_cb->GetValue(),wxOK);
              dialog.ShowModal();
            }
          GetLocalFiles(wxGetCwd());
        }
    }
}
void HarborDialog::OnLocalPWD( wxCommandEvent &event )
{

  if (!(wxSetWorkingDirectory(local_pwd_cb->GetValue())))
    {
      wxMessageDialog dialog(this, "Cant change to that directory,...aborting",local_pwd_cb->GetValue(),wxOK);
      dialog.ShowModal();
    }
  GetLocalFiles(wxGetCwd());

}

void HarborDialog::OnLocalBeginDrag( wxListEvent &event )
{
    
}

void HarborDialog::OnLocalRightClick( wxMouseEvent &event )
{
  MyPopupMenu menu("Local");
  menu.Append( ID_LOCAL_NEW_DIRECTORY_RC, "New Directory", "" );
  menu.Append( ID_LOCAL_NEW_FILE_RC, "New File", "" );
  menu.Append( ID_LOCAL_REMOVE_RC, "Remove", "" );
  menu.AppendSeparator();
  menu.Append( ID_LOCAL_PUT_RC, "Put ", "" );
  menu.AppendSeparator();
  menu.Append( ID_LOCAL_OPENR_RC, "Open", "" );
  menu.Append( ID_LOCAL_OPENP_RC, "Open in Programmer's Editor", "" );
  PopupMenu(&menu, event.GetX(),event.GetY());
}

void HarborDialog::OnLocalActivated(wxListEvent &event)
{

  int sel, sel_type;
  
  wxString file;
  wxString cwd;

  cwd= wxGetCwd() + "\\";
  
  sel = GetSelected(HarborDialog::local_list);
  sel_type = HarborDialog::local_list->GetItemData(sel);
  file = HarborDialog::local_list->GetItemText(sel);
  switch (sel_type)
    {
    case 0:
      {

        if (!(wxSetWorkingDirectory(file)))
          {
            wxMessageDialog dialog(this, "Could not Change Directories, aborting...", "Error: Direcroy", wxOK);
            dialog.ShowModal();
            break;
          }
        GetLocalFiles(wxGetCwd());
        
        break;
      }


    case 1:
      {
        wxString temp = GetRegularEditor() + " \"" + cwd + file + "\"";
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not open Regular Editor, aborting...", GetRegularEditor(), wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;

      }
    case 2:
      {
        wxMessageDialog dialog(this, "Shall I open with regular editor ?","Edit?",wxYES_NO | wxICON_INFORMATION);
        if (dialog.ShowModal() == wxID_YES)
          {

            wxString temp = GetRegularEditor() + " \"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", GetRegularEditor(), wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
          }
        
        break;
      }
    case 3:
      {
              wxString temp = cwd + file;
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not execute, aborting...", "Error: Couldn't execute", wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;
      }

    case 4:
      {
        wxString temp = "C:\\Program Files\\Windows Media Player\\mplayer2.exe \"" + cwd + file + "\"";
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", "Error: Programming Editor", wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;
      }
    case 5:
      {
        wxString temp = "C:\\Program Files\\Windows Media Player\\mplayer2.exe \"" +  cwd + file + "\"";
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", "Error: Programming Editor", wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;
      }
    case 6:
      {
        if (file.Contains(".bmp"))
          {
            wxString temp = "C:\\Program Files\\Accessories\\MSPAINT.EXE \"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", "Error: Programming Editor", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }

          }
        else
          {
            wxString temp = "C:\\Windows\\explorer.exe \"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", "Error: Programming Editor", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
          }
        break;
      }

    case 7:
      {
        wxString temp = GetRegularEditor() + " \"" + cwd + file + "\"";
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not open Regular Editor, aborting...", "Error: Regular Editor", wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;

      }
    case 8:
      {
        if (!(wxFileExists("C:\\Program Files\\Winzip\\winzip32.exe")))
          {
            wxMessageDialog dialog(this, "Hmm, I can't find winzip, you sure you have it ?","Error: Missing Program",wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        else
          {
            wxString temp = "C:\\Program Files\\Winzip\\winzip32.exe \"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not execute Winzip, aborting...", "Error: No Winzip", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
          }
        break;
      }
    case 9 :
      {
                if (!(wxFileExists("C:\\Program Files\\Winzip\\winzip32.exe")))
          {
            wxMessageDialog dialog(this, "Hmm, I can't find winzip, you sure you have it ?","Error: Missing Program",wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        else
          {
            wxString temp = "C:\\Program Files\\Winzip\\winzip32.exe \"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not execute Winzip, aborting...", "Error: No Winzip", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
          }
        break;
      }
    case 10:
      {
        wxString temp = GetProgrammingEditor() + " \"" + cwd + file + "\"";
        if (!(wxExecute(temp)))
          {
            wxMessageDialog dialog(this, "Could not open Programming Editor, aborting...", GetProgrammingEditor(), wxOK | wxICON_ERROR);
            dialog.ShowModal();
          }
        break;
      }
    case 11 :
      {
        wxMessageDialog d(this, "Not sure what type of file this is, shall i open with Regular Editor?","Question: File type",wxYES_NO);
        if (d.ShowModal() == wxID_YES)
          {
            wxString temp = GetRegularEditor() + "\"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not open Regular Editor, aborting...", "Error: Regular Editor", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
            break;
          }
        else
          break;
      }   
    default:
      {
        wxMessageDialog d(this, "Not sure what type of file this is, shall i open with Regular Editor?","Question: File type",wxYES_NO);
        if (d.ShowModal() == wxID_YES)
          {
            wxString temp = GetRegularEditor() + "\"" + cwd + file + "\"";
            if (!(wxExecute(temp)))
              {
                wxMessageDialog dialog(this, "Could not open Regular Editor, aborting...", "Error: Regular Editor", wxOK | wxICON_ERROR);
                dialog.ShowModal();
              }
            break;
          }
        else
          break;
      }
    }
    
}
  

   


void HarborDialog::GetLocalFiles(wxString directory)
{
  wxString size;
//   wxString file_array[1000];
//   wxString dir_array[1000];

  vector<wxString> dir_v;
  vector<wxString> file_v;

  wxString dirname, filename, size_test;

  int i = 0, f = 0,index = 0;
  int icon_type = 10;

  unsigned long long_size;
  float float_size;
  bool cont, status;

  wxDir dir(directory);
  if (!(dir.IsOpened()))
    return;
  cont = dir.GetFirst(&dirname, wxEmptyString, wxDIR_DIRS);
  while (cont)
    {
      
      dir_v.push_back(dirname);
      cont = dir.GetNext(&dirname);
    }

  i = 0;


  cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_FILES | wxDIR_HIDDEN);
  while (cont)
    {
      file_v.push_back(filename);
      cont = dir.GetNext(&filename);
    }


  NoCaseSort a;
  sort(dir_v.begin(),dir_v.end(),a);
  sort(file_v.begin(),file_v.end(),a);
//   SortList(dir_v,dir_v.size());
//   SortList(file_v,file_v.size());
  

  HarborDialog::local_list->DeleteAllItems();


  for (int j = 0;j < dir_v.size();j++)
    {
      HarborDialog::local_list->InsertItem(index, dir_v[j],0);
      HarborDialog::local_list->SetItem(index,1,"Dir");
      HarborDialog::local_list->SetItem(index,2,"4096");
      HarborDialog::local_list->SetItemData(index,0);
      index++;
    }
  


// = HERE WE START THE FOR LOOPS WHERE WE ADD THE FILES .....STUPID!
// =
// =
// =
// =
// ================================================================

  wxString Types, temp;
  HANDLE fhandle;
  BY_HANDLE_FILE_INFORMATION info;

  for (int k = 0;k < file_v.size();k++)
    {
     

      if ((fhandle = CreateFile(file_v[k].c_str(),0, FILE_SHARE_READ, 0,OPEN_EXISTING,0,0)) == INVALID_HANDLE_VALUE)
        {
          size = "Unknown";
          LPVOID lpMsgBuf;
          
//           FormatMessage(
//                         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
//                         NULL,
//                         GetLastError(),
//                         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
//                         (LPTSTR) &lpMsgBuf,
//                         0,
//                         NULL
//                         );
//          wxMessageDialog dialog(this, (const char*)lpMsgBuf,file_v[k],wxOK);
//          dialog.ShowModal();

        }
      
      else
        {
          if (!(status = GetFileInformationByHandle(fhandle, &info)))
            {
              size = "Unknown";
            }
          else
            {
              long_size = info.nFileSizeLow;
              float_size = (float)long_size / 100;
              size.sprintf("%.2f",float_size);
              size[size.Length() - 1] = 'K';
            }
        }
      CloseHandle(fhandle);

// = =====================================
// =
// = BELOW I JUST SEARCH FOR DIFFERENT EXTENSIONS AND ASSIGN THE VALUE APPROPRIATELY
// =
// =
// =======================================
          
  
      if (file_v[k].AfterLast('.').IsSameAs("txt"))
        {
          Types = "Text";
          icon_type = 1;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("doc"))
        {
          Types = "doc";
          icon_type = 2;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("exe"))
        {
          Types = "exe";
          icon_type = 3;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("mp3") || file_v[k].AfterLast('.').IsSameAs("wav"))
        {
          Types = "music";
          icon_type = 4;
        }
      else if ((file_v[k].AfterLast('.').IsSameAs("mpeg")) || (file_v[k].AfterLast('.').IsSameAs("avi")) ||
               (file_v[k].AfterLast('.').IsSameAs("asf")) ||  (file_v[k].AfterLast('.').IsSameAs("ra")) ||
               (file_v[k].AfterLast('.').IsSameAs("mpg")) ||  (file_v[k].AfterLast('.').IsSameAs("mov")))
        {
          Types = "movie";
          icon_type = 5;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("gif") || file_v[k].AfterLast('.').IsSameAs("jpg") ||
               (file_v[k].AfterLast('.').IsSameAs("jpeg")) || (file_v[k].AfterLast('.').IsSameAs("bmp")))
        {
          Types = "picture";
          icon_type = 6;
        }
      else if (file_v[k].CmpNoCase("readme") == 0)
        {
          Types = "Readme";
          icon_type = 7;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("bat") || file_v[k].AfterLast('.').IsSameAs("sys") ||
               file_v[k].AfterLast('.').IsSameAs("dll") || file_v[k].AfterLast('.').IsSameAs("la"))
        {
          Types = "System File";
            icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("zip") || file_v[k].AfterLast('.').IsSameAs("rpm"))
        {
          Types = "zip";
          icon_type = 8;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("tgz") || file_v[k].AfterLast('.').IsSameAs("gz") || file_v[k].AfterLast('.').IsSameAs("bz2"))
        {
          Types = "tgz";
          icon_type = 9;
        }
      else if (file_v[k].AfterLast('.').Contains("cpp") || (file_v[k].AfterLast('.').Contains("hpp")))
        {
          Types = "C++";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs('c') || (file_v[k].AfterLast('.').IsSameAs('h')))
        {
          Types = "C";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs('o'))
        {
          Types = "Object File";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("pl") || file_v[k].AfterLast('.').IsSameAs("cgi") ||
               file_v[k].AfterLast('.').IsSameAs("pm"))
        {
          Types = "Perl";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').Contains("html"))
        {
          Types = "HTML";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("py"))
        {
          Types = "Python!";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').Contains("php"))
        {
          Types = "PHP";
          icon_type = 10;
        }
      else if (file_v[k].Contains("Makefile"))
        {
          Types = "Makefile";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("rc"))
        {
          Types = "Windows Resource";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("el"))
        {
          Types = "Elisp";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("cl"))
        {
          Types = "Common Lisp";
          icon_type = 10;
        }

      else if (file_v[k].AfterLast('.').IsSameAs("java") || file_v[k].AfterLast('.').IsSameAs("class"))
        {
          Types = "Java";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("rb"))
        {
          Types = "Ruby";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("m3"))
        {
          Types = "Modula3";
          icon_type = 10;
        }
      else if (file_v[k].AfterLast('.').IsSameAs("ss") || file_v[k].AfterLast('.').IsSameAs("scm"))
        {
          Types = "Scheme";
          icon_type = 10;
        }
      else if (file_v[k][file_v[k].Length() - 1] == '~')
        {
          Types = "Emacs autosave";
          icon_type = 10;
        }
      else
        {
          Types = "Unkown";
          icon_type = 2;
        }
    
      
      HarborDialog::local_list->InsertItem(index, file_v[k],icon_type);
      HarborDialog::local_list->SetItem(index,1,Types);
      HarborDialog::local_list->SetItem(index,2,size);
      HarborDialog::local_list->SetItemData(index,icon_type);
      index++;
    }


  local_pwd_cb->Append(wxGetCwd());
  local_pwd_cb->SetValue(wxGetCwd());

}


bool HarborDialog::SortList(vector<wxString> &T, int num_of_elements)
{
  int i = 0, j = 0;
  wxString hold;

  for (i = 0;i < num_of_elements - 1;i++)
    {
      for (j = 0;j <  num_of_elements - 1;j++)
        {
          if ((T[j + 1].CmpNoCase(T[j])) < 0)
            {
              hold = T[j + 1];
              T[j + 1] = T[j];
              T[j] = hold;
            }
        }
    }
    
  return true;
}