/**********************************************************************
 This file is based on TQt Designer, Copyright (C) 2000 Trolltech AS. �All rights reserved.

 This file may be distributed and/or modified under the terms of the
 GNU General Public License version 2 as published by the Free Software
 Foundation and appearing in the file LICENSE.GPL included in the
 packaging of this file.

 This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

 See http://www.trolltech.com/gpl/ for GPL licensing information.

 Modified for Kommander:
  (C) 2004      Michal Rudolf <mrudolf@kdewebdev.org>

**********************************************************************/

#include "newformimpl.h"
#include "mainwindow.h"
#include "pixmapchooser.h"
#include "metadatabase.h"
#include "formwindow.h"
#include "widgetfactory.h"
#include "widgetdatabase.h"
#include "actioneditorimpl.h"
#include "hierarchyview.h"
#include "resource.h"
#include "formfile.h"

#include <tqiconview.h>
#include <tqlabel.h>
#include <tqfileinfo.h>
#include <tqdir.h>
#include <tqregexp.h>
#include <tqpushbutton.h>
#include <stdlib.h>
#include <tqcombobox.h>
#include <tqworkspace.h>
#include <tqmessagebox.h>

#include <tdelocale.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>

#include "dialog.h"

static int _forms = 0;

FormItem::FormItem(TQIconView *view, const TQString &text)    : NewItem(view, text)
{
}

void FormItem::insert()
{
  TQString n = "Form" + TQString::number(++_forms);
  FormWindow *fw = 0;
  FormFile *ff = new FormFile(FormFile::createUnnamedFileName(), true);
  fw = new FormWindow(ff, MainWindow::self, MainWindow::self->qWorkspace(), n);
  MetaDataBase::addEntry(TQT_TQOBJECT(fw));
  TQWidget *w = 0L;
  if (fType == Dialog) 
  {
    w = WidgetFactory::create(WidgetDatabase::idFromClassName("Dialog"), fw, n.latin1());
    fw->setMainContainer(w);
  } 
  else if (fType == Wizard)
  {
    w = WidgetFactory::create(WidgetDatabase::idFromClassName("Wizard"), fw, n.latin1());
    fw->setMainContainer(w);
  }
  if (w)
  {
    w->setProperty("useInternalParser", true);
    MetaDataBase::setPropertyChanged(TQT_TQOBJECT(w), "useInternalParser", true);
  }
  fw->setCaption(n);
  fw->resize(600, 480);
  MainWindow::self->insertFormWindow(fw);

  // the wizard might have changed a lot, lets update everything
  MainWindow::self->actioneditor()->setFormWindow(fw);
  MainWindow::self->objectHierarchy()->setFormWindow(fw, fw);
  fw->killAccels(TQT_TQOBJECT(fw));
  fw->setFocus();
}



CustomFormItem::CustomFormItem(TQIconView *view, const TQString &text)
    : NewItem(view, text)
{
}

static void unifyFormName(FormWindow *fw, TQWorkspace *qworkspace)
{
  TQStringList lst;
  TQWidgetList windows = qworkspace->windowList();
  for (TQWidget* w = windows.first(); w; w = windows.next())
    if (w != fw)
      lst << w->name();
  
  if (lst.findIndex(fw->name()) == -1)
    return;
  TQString origName = fw->name();
  TQString n = origName;
  int i = 1;
  while (lst.findIndex(n) != -1)
    n = origName + TQString::number(i++);
  fw->setName(n);
  fw->setCaption(n);
}

void CustomFormItem::insert()
{
  TQString filename = templateFileName();
  if (!filename.isEmpty() && TQFile::exists(filename))
  {
    Resource resource(MainWindow::self);
    FormFile *ff = new FormFile(filename, true);
    if (!resource.load(ff))
    {
      TQMessageBox::information(MainWindow::self, i18n("Load Template"),
          i18n("Could not load form description from template '%1'").arg(filename));
      delete ff;
      return;
    }
    ff->setFileName(TQString());
    if (MainWindow::self->formWindow())
    {
      MainWindow::self->formWindow()->setFileName(TQString());
      unifyFormName(MainWindow::self->formWindow(), MainWindow::self->qWorkspace());
    }
  }
}


NewForm::NewForm(TQWidget *parent, const TQString &templatePath)
    : NewFormBase(parent, 0, true)
{
  connect(helpButton, TQT_SIGNAL(clicked()), MainWindow::self, TQT_SLOT(showDialogHelp()));

  TQIconViewItem *cur = 0;
  FormItem *fi = new FormItem(templateView, i18n("Dialog"));
  allItems.append(fi);
  fi->setFormType(FormItem::Dialog);
  fi->setPixmap(PixmapChooser::loadPixmap("newform.xpm"));
  fi->setDragEnabled(false);
  cur = fi;
  fi = new FormItem(templateView, i18n("Wizard"));
  allItems.append(fi);
  fi->setFormType(FormItem::Wizard);
  fi->setPixmap(PixmapChooser::loadPixmap("newform.xpm"));
  fi->setDragEnabled(false);


  TQStringList searchPaths = TDEGlobal::dirs()->findDirs("data", "kmdr-editor/templates");
  if (!templatePath.isEmpty())
    searchPaths.append(templatePath);
  
  
  // search each path
  for (TQStringList::ConstIterator it = searchPaths.begin(); it != searchPaths.end(); ++it)
  {
    if (!TQFile::exists(*it))
      continue;
    TQDir dir(*it);
    const TQFileInfoList* fileList = dir.entryInfoList(TQDir::DefaultFilter, TQDir::DirsFirst | TQDir::Name);
    if (fileList)
      for (TQFileInfoListIterator fit(*fileList); fit.current(); ++fit)
      {
        TQFileInfo* fi = fit.current();
        if (!fi->isFile() || fi->extension() != "kmdr")
          continue;
        TQString name = fi->baseName();
        name = name.replace("_", " ");
        CustomFormItem *ci = new CustomFormItem(templateView, name);
        allItems.append(ci);
        ci->setDragEnabled(false);
        ci->setPixmap(PixmapChooser::loadPixmap("newform.xpm"));
        ci->setTemplateFile(fi->absFilePath());
      }
  }
  templateView->viewport()->setFocus();
  templateView->setCurrentItem(cur);
}

void NewForm::accept()
{
  if (!templateView->currentItem())
    return;
  ((NewItem *) templateView->currentItem())->insert();
  NewFormBase::accept();
}


void NewForm::itemChanged(TQIconViewItem *item)
{
    Q_UNUSED(item);
}

#include "newformimpl.moc"
