// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.

#include <IFSelect_SelectPointed.hxx>
#include <IFSelect_SelectSuite.hxx>
#include <Interface_EntityIterator.hxx>
#include <Interface_Graph.hxx>
#include <Standard_Type.hxx>
#include <TCollection_AsciiString.hxx>

#include <cstdio>
IMPLEMENT_STANDARD_RTTIEXT(IFSelect_SelectSuite, IFSelect_SelectDeduct)

IFSelect_SelectSuite::IFSelect_SelectSuite() = default;

bool IFSelect_SelectSuite::AddInput(const occ::handle<IFSelect_Selection>& item)
{
  if (item.IsNull())
    return false;
  occ::handle<IFSelect_Selection> input = Input();
  if (!input.IsNull())
    return false;
  occ::handle<IFSelect_SelectDeduct> first = occ::down_cast<IFSelect_SelectDeduct>(item);
  if (first.IsNull())
    SetInput(item);
  else
    thesel.Prepend(item);
  return true;
}

void IFSelect_SelectSuite::AddPrevious(const occ::handle<IFSelect_SelectDeduct>& item)
{
  if (!item.IsNull())
    thesel.Prepend(item);
}

void IFSelect_SelectSuite::AddNext(const occ::handle<IFSelect_SelectDeduct>& item)
{
  if (!item.IsNull())
    thesel.Append(item);
}

int IFSelect_SelectSuite::NbItems() const
{
  return thesel.Length();
}

occ::handle<IFSelect_SelectDeduct> IFSelect_SelectSuite::Item(const int num) const
{
  return occ::down_cast<IFSelect_SelectDeduct>(thesel.Value(num));
}

void IFSelect_SelectSuite::SetLabel(const char* lab)
{
  thelab.Clear();
  thelab.AssignCat(lab);
}

Interface_EntityIterator IFSelect_SelectSuite::RootResult(const Interface_Graph& G) const
{
  Interface_EntityIterator iter;
  bool                     firstin = (HasInput() || HasAlternate());
  if (firstin)
    iter = InputResult(G);
  //   Starting : we take the Input/Alternate IF one of the 2 is set
  //   Otherwise, we start on the basic definition of the first selection

  int i, nb = NbItems();
  for (i = 1; i <= nb; i++)
  {
    occ::handle<IFSelect_SelectDeduct> anitem = Item(i);
    if (firstin)
      anitem->Alternate()->SetList(iter.Content());
    firstin = true; // then it's systematic
    iter    = anitem->UniqueResult(G);
  }
  return iter;
}

TCollection_AsciiString IFSelect_SelectSuite::Label() const
{
  if (thelab.Length() > 0)
    return thelab;
  char txt[100];
  Sprintf(txt, "Suite of %d Selections", NbItems());
  TCollection_AsciiString lab(txt);
  return lab;
}
