/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2015 Jean-Pierre Charras, jp.charras at wanadoo.fr
 * Copyright (C) 1992-2015 KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

/**
 * @file sch_sheet.h
 * @brief Definition of the SCH_SHEET class for Eeschema.
 */

#ifndef SCH_SHEEET_H
#define SCH_SHEEET_H

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/foreach.hpp>
#include <sch_text.h>
#include <sch_reference_list.h>


class PART_LIBS;
class LINE_READER;
class SCH_SCREEN;
class SCH_SHEET;
class SCH_SHEET_PIN;
class SCH_SHEET_PATH;
class DANGLING_END_ITEM;
class SCH_EDIT_FRAME;
class NETLIST_OBJECT_LIST;


#define MIN_SHEET_WIDTH  500
#define MIN_SHEET_HEIGHT 150


/**
 * Class SCH_SHEET_PIN
 * defines a sheet pin (label) used in sheets to create hierarchical schematics.
 *
 * A SCH_SHEET_PIN is used to create a hierarchical sheet in the same way a
 * pin is used in a component.  It connects the objects in the sheet object
 * to the objects in the schematic page to the objects in the page that is
 * represented by the sheet.  In a sheet object, a SCH_SHEET_PIN must be
 * connected to a wire, bus, or label.  In the schematic page represented by
 * the sheet, it corresponds to a hierarchical label.
 */
class SCH_SHEET_PIN : public SCH_HIERLABEL
{
private:
    int m_number;       ///< Label number use for saving sheet label to file.
                        ///< Sheet label numbering begins at 2.
                        ///< 0 is reserved for the sheet name.
                        ///< 1 is reserve for the sheet file name.

    /**
     * Defines the edge of the sheet that the sheet pin is positioned
     * SHEET_LEFT_SIDE = 0: pin on left side
     * SHEET_RIGHT_SIDE = 1: pin on right side
     * SHEET_TOP_SIDE = 2: pin on top side
     * SHEET_BOTTOM_SIDE =3: pin on bottom side
     *
     * For compatibility reasons, this does not follow same values as text orientation.
     */
    enum SHEET_SIDE
    {
        SHEET_LEFT_SIDE = 0,
        SHEET_RIGHT_SIDE,
        SHEET_TOP_SIDE,
        SHEET_BOTTOM_SIDE,
        SHEET_UNDEFINED_SIDE
    };
    SHEET_SIDE m_edge;

public:
    SCH_SHEET_PIN( SCH_SHEET* parent,
                   const wxPoint& pos = wxPoint( 0, 0 ),
                   const wxString& text = wxEmptyString );

    // Do not create a copy constructor.  The one generated by the compiler is adequate.

    ~SCH_SHEET_PIN() { }

    wxString GetClass() const
    {
        return wxT( "SCH_SHEET_PIN" );
    }

    bool operator ==( const SCH_SHEET_PIN* aPin ) const;

    /**
     * Virtual function IsMovableFromAnchorPoint
     * Return true for items which are moved with the anchor point at mouse cursor
     * and false for items moved with no reference to anchor (usually large items)
     * @return true for a hierarchical sheet pin
     */
    bool IsMovableFromAnchorPoint() { return true; }

    void Draw( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wxPoint& aOffset,
               GR_DRAWMODE aDrawMode, EDA_COLOR_T aColor = UNSPECIFIED_COLOR );

    /**
     * Function CreateGraphicShape (virtual)
     * Calculates the graphic shape (a polygon) associated to the text
     * @param aPoints = a buffer to fill with polygon corners coordinates
     * @param aPos = Position of the shape
     */
    void CreateGraphicShape( std::vector <wxPoint>& aPoints, const wxPoint& aPos );

    void SwapData( SCH_ITEM* aItem );

    int GetPenSize() const;

    /**
     * Get the sheet label number.
     *
     * @return Number of the sheet label.
     */
    int GetNumber() const { return m_number; }

    /**
     * Set the sheet label number.
     *
     * @param aNumber - New sheet number label.
     */
    void SetNumber( int aNumber );

    void SetEdge( SHEET_SIDE aEdge );

    SHEET_SIDE GetEdge() const;

    /**
     * Function ConstrainOnEdge
     * is used to adjust label position to edge based on proximity to vertical / horizontal edge
     * of the parent sheet.
     */
    void ConstrainOnEdge( wxPoint Pos );

    /**
     * Get the parent sheet object of this sheet pin.
     *
     * @return The sheet that is the parent of this sheet pin or NULL if it does
     *         not have a parent.
     */
    SCH_SHEET* GetParent() const { return (SCH_SHEET*) m_Parent; }

    bool Save( FILE* aFile ) const;

    bool Load( LINE_READER& aLine, wxString& aErrorMsg );

#if defined(DEBUG)
    void Show( int nestLevel, std::ostream& os ) const;     // override
#endif

    // Geometric transforms (used in block operations):

    void Move( const wxPoint& aMoveVector )
    {
        m_Pos += aMoveVector;
    }

    void MirrorY( int aYaxis_position );

    void Rotate( wxPoint aPosition );

    void MirrorX( int aXaxis_position );

    bool Matches( wxFindReplaceData& aSearchData, void* aAuxData, wxPoint* aFindLocation );

    bool Replace( wxFindReplaceData& aSearchData, void* aAuxData = NULL )
    {
        return EDA_ITEM::Replace( aSearchData, m_Text );
    }

    bool IsReplaceable() const { return true; }

    void GetEndPoints( std::vector< DANGLING_END_ITEM >& aItemList );

    bool IsConnectable() const { return true; }

    wxString GetSelectMenuText() const;

    BITMAP_DEF GetMenuImage() const { return  add_hierar_pin_xpm; }

    void SetPosition( const wxPoint& aPosition ) { ConstrainOnEdge( aPosition ); }

    bool HitTest( const wxPoint& aPosition, int aAccuracy ) const;

    EDA_ITEM* Clone() const;
};


typedef boost::ptr_vector<SCH_SHEET_PIN> SCH_SHEET_PINS;


/**
 * Class SCH_SHEET
 * is the sheet symbol placed in a schematic, and is the entry point for a sub schematic.
 */
class SCH_SHEET : public SCH_ITEM
{
    friend class SCH_SHEET_PIN;

    /// Screen that contains the physical data for the sheet.  In complex hierarchies
    /// multiple sheets can share a common screen.
    SCH_SCREEN* m_screen;

    /// The list of sheet connection points.
    SCH_SHEET_PINS m_pins;

    /// The file name is also in the #SCH_SCREEN object associated with the sheet.  It is
    /// also needed here for loading after reading the sheet description from file.
    wxString m_fileName;

    /// This is equivalent to the reference designator for components and is stored in F0
    /// sheet pin in the schematic file.
    wxString m_name;

    /// The height of the text used to draw the sheet name.
    int m_sheetNameSize;

    /// The height of the text used to draw the file name.
    int m_fileNameSize;

    /// The position of the sheet.
    wxPoint m_pos;

    /// The size of the sheet.
    wxSize m_size;

    /// The sheet number ordered by file load.
    // @todo: At some point this should really be a sheet number assigned by the user rather
    //        than assigned in the order the sheets were parsed and loaded.
    int m_number;

    SCH_SHEET* getRootSheet();

public:
    SCH_SHEET( const wxPoint& pos = wxPoint( 0, 0 ) );

    /**
     * Copy Constructor
     * clones \a aSheet into a new object.  All sheet pins are copied as is except and
     * the SCH_SHEET_PIN's #m_Parent pointers are set to the new copied parent object.
     */
    SCH_SHEET( const SCH_SHEET& aSheet );

    ~SCH_SHEET();

    wxString GetClass() const
    {
        return wxT( "SCH_SHEET" );
    }

    /**
     * Virtual function IsMovableFromAnchorPoint
     * Return true for items which are moved with the anchor point at mouse cursor
     *  and false for items moved with no reference to anchor
     * Usually return true for small items (labels, junctions) and false for
     * items which can be large (hierarchical sheets, components)
     * @return false for a hierarchical sheet
     */
    bool IsMovableFromAnchorPoint() { return false; }

    wxString GetName() const { return m_name; }

    void SetName( const wxString& aName ) { m_name = aName; }

    int GetSheetNameSize() const { return m_sheetNameSize; }

    void SetSheetNameSize( int aSize ) { m_sheetNameSize = aSize; }

    int GetFileNameSize() const { return m_fileNameSize; }

    void SetFileNameSize( int aSize ) { m_fileNameSize = aSize; }

    SCH_SCREEN* GetScreen() { return m_screen; }

    wxSize GetSize() { return m_size; }

    void SetSize( const wxSize& aSize ) { m_size = aSize; }

    /**
     * Function SetScreen
     * sets the screen associated with this sheet to \a aScreen.
     * <p>
     * The screen reference counting is performed by SetScreen.  If \a aScreen is not
     * the same as the current screen, the current screen reference count is decremented
     * and \a aScreen becomes the screen for the sheet.  If the current screen reference
     * count reaches zero, the current screen is deleted.  NULL is a valid value for
     * \a aScreen.
     * </p>
     * @param aScreen The new screen to associate with the sheet.
     */
    void SetScreen( SCH_SCREEN* aScreen );

    /**
     * Function GetScreenCount
     * returns the number of times the associated screen for the sheet is being used.  If
     * no screen is associated with the sheet, then zero is returned.
     */
    int GetScreenCount() const;

    bool Save( FILE* aFile ) const;

    bool Load( LINE_READER& aLine, wxString& aErrorMsg );

    void GetMsgPanelInfo( std::vector< MSG_PANEL_ITEM >& aList );

    /* there is no member for orientation in sch_sheet, to preserve file
     * format, we detect orientation based on pin edges
     */
    bool IsVerticalOrientation() const;

    /**
     * Add aSheetPin to the sheet.
     *
     * Note: Once a sheet pin is added to the sheet, it is owned by the sheet.
     *       Do not delete the sheet pin object or you will likely get a segfault
     *       when the sheet is destroyed.
     *
     * @param aSheetPin The sheet pin item to add to the sheet.
     */
    void AddPin( SCH_SHEET_PIN* aSheetPin );

    SCH_SHEET_PINS& GetPins() { return m_pins; }

    SCH_SHEET_PINS& GetPins() const
    {
        return const_cast< SCH_SHEET_PINS& >( m_pins );
    }

    /**
     * Remove \a aSheetPin from the sheet.
     *
     * @param aSheetPin The sheet pin item to remove from the sheet.
     */
    void RemovePin( SCH_SHEET_PIN* aSheetPin );

    /**
     * Delete sheet label which do not have a corresponding hierarchical label.
     *
     * Note: Make sure you save a copy of the sheet in the undo list before calling
     *       CleanupSheet() otherwise any unreferenced sheet labels will be lost.
     */
    void CleanupSheet();

    /**
     * Return the sheet pin item found at \a aPosition in the sheet.
     *
     * @param aPosition The position to check for a sheet pin.
     *
     * @return The sheet pin found at \a aPosition or NULL if no sheet pin is found.
     */
    SCH_SHEET_PIN* GetPin( const wxPoint& aPosition );

    /**
     * Checks if the sheet already has a sheet pin named \a aName.
     *
     * @param aName Name of the sheet pin to search for.
     *
     * @return  True if sheet pin with \a aName is found, otherwise false.
     */
    bool HasPin( const wxString& aName );

    bool HasPins() { return !m_pins.empty(); }

    /**
     * Check all sheet labels against schematic for undefined hierarchical labels.
     *
     * @return True if there are any undefined labels.
     */
    bool HasUndefinedPins();

    /**
     * Function GetMinWidth
     * returns the minimum width of the sheet based on the widths of the sheet pin text.
     *
     * <p>
     * The minimum sheet width is determined by the width of the bounding box of each
     * hierarchical sheet pin.  If two pins are horizontally adjacent ( same Y position )
     * to each other, the sum of the bounding box widths is used.  If at some point in
     * the future sheet objects can be rotated or pins can be placed in the vertical
     * orientation, this function will need to be changed.
     * </p>
     *
     * @return The minimum width the sheet can be resized.
     */
    int GetMinWidth() const;

    /**
     * Function GetMinHeight
     * returns the minimum height that the sheet can be resized based on the sheet pin
     * positions.
     *
     * <p>
     * The minimum width of a sheet is determined by the Y axis location of the bottom
     * most sheet pin.  If at some point in the future sheet objects can be rotated or
     * pins can be placed in the vertical orientation, this function will need to be
     * changed.
     * </p>
     *
     * @return The minimum height the sheet can be resized.
     */
    int GetMinHeight() const;

    int GetPenSize() const;

    void Draw( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wxPoint& aOffset,
               GR_DRAWMODE aDrawMode, EDA_COLOR_T aColor = UNSPECIFIED_COLOR );

    EDA_RECT const GetBoundingBox() const;

    /**
     * Function GetResizePos
     * returns the position of the lower right corner of the sheet in drawing units.
     *
     * @return A wxPoint containing lower right corner of the sheet in drawing units.
     */
    wxPoint GetResizePosition() const;

    void SwapData( SCH_ITEM* aItem );

    /**
     * Function ComponentCount
     *  count our own components, without the power components.
     *  @return the component count.
     */
    int ComponentCount();

    /**
     * Function Load.
     *  for the sheet: load the file m_fileName
     *  if a screen already exists, the file is already read.
     *  m_screen point on the screen, and its m_RefCount is
     * incremented
     *  else creates a new associated screen and load the data file.
     *  @param aFrame = a SCH_EDIT_FRAME pointer to the maim schematic frame
     *  @return true if OK
     */
    bool Load( SCH_EDIT_FRAME* aFrame );

    /**
     * Function SearchHierarchy
     *  search the existing hierarchy for an instance of screen "FileName".
     *  @param aFilename = the filename to find
     *  @param aScreen = a location to return a pointer to the screen (if found)
     *  @return bool if found, and a pointer to the screen
     */
    bool SearchHierarchy( const wxString& aFilename, SCH_SCREEN** aScreen );

    /**
     * Function CountSheets
     * calculates the number of sheets found in "this"
     * this number includes the full subsheets count
     * @return the full count of sheets+subsheets contained by "this"
     */
    int CountSheets();

    /**
     * Function GetFileName
     * return the filename corresponding to this sheet
     * @return a wxString containing the filename
     */
    wxString GetFileName( void ) const;

    // Set a new filename without changing anything else
    void SetFileName( const wxString& aFilename )
    {
        m_fileName = aFilename;
        // Filenames are stored using unix notation
        m_fileName.Replace( wxT( "\\" ), wxT( "/" ) );
    }

    bool ChangeFileName( SCH_EDIT_FRAME* aFrame, const wxString& aFileName );

    //void      RemoveSheet(SCH_SHEET* sheet);
    //to remove a sheet, just delete it
    //-- the destructor should take care of everything else.

    // Geometric transforms (used in block operations):

    void Move( const wxPoint& aMoveVector )
    {
        m_pos += aMoveVector;

        BOOST_FOREACH( SCH_SHEET_PIN& pin, m_pins )
        {
            pin.Move( aMoveVector );
        }
    }

    void MirrorY( int aYaxis_position );

    void MirrorX( int aXaxis_position );

    void Rotate( wxPoint aPosition );

    bool Matches( wxFindReplaceData& aSearchData, void* aAuxData, wxPoint* aFindLocation );

    bool Replace( wxFindReplaceData& aSearchData, void* aAuxData = NULL );

    bool IsReplaceable() const { return true; }

    /**
     * Resize this sheet to aSize and adjust all of the labels accordingly.
     *
     * @param aSize - The new size for this sheet.
     */
    void Resize( const wxSize& aSize );

    /**
     * Function GetSheetNamePosition
     * @return the position of the anchor of sheet name text
     */
    wxPoint GetSheetNamePosition();

    /**
     * Function GetFileNamePosition
     * @return the position of the anchor of filename text
     */
    wxPoint GetFileNamePosition();

    void GetEndPoints( std::vector <DANGLING_END_ITEM>& aItemList );

    bool IsDanglingStateChanged( std::vector< DANGLING_END_ITEM >& aItemList );

    bool IsDangling() const;

    bool IsSelectStateChanged( const wxRect& aRect );

    bool IsConnectable() const { return true; }

    void GetConnectionPoints( std::vector< wxPoint >& aPoints ) const;

    SEARCH_RESULT Visit( INSPECTOR* inspector, const void* testData,
                         const KICAD_T scanTypes[] );

    wxString GetSelectMenuText() const;

    BITMAP_DEF GetMenuImage() const { return add_hierarchical_subsheet_xpm; }

    void GetNetListItem( NETLIST_OBJECT_LIST& aNetListItems,
                         SCH_SHEET_PATH*      aSheetPath );

    SCH_ITEM& operator=( const SCH_ITEM& aSheet );

    /**
     * Operator <
     *
     * test if a \a aRhs is less than this sheet.
     *
     * Sheet comparison order is:
     * The number of parent sheets of this sheet is less than \a aRhs.
     * When the number of parent sheets for this sheet are the same as \a aRhs, the time
     * stamps of each parent sheet are compared from the root sheet to the last sheet.
     *
     * @param aRhs is an SCH_SHEET reference to the right hand side of the comparison.
     * @return true if this #SCH_SHEET is less than \a aRhs.
     */
    bool operator<( const SCH_SHEET& aRhs ) const;

    /**
     * Structure SortByPath
     *
     * tests if \a aLhs is less than \a aRhs.
     *
     * @param aLhs is the left hand side reference to a #SCH_SHEET for comparison.
     * @param aRhs is the right hand side reference to a #SCH_SHEET for comparison.
     * @return true if \a aLhs is less than \a aRhs otherwise false.
     */
    struct SortByPath
    {
        bool operator()( const SCH_SHEET* aLhs, const SCH_SHEET* aRhs )
        {
            wxCHECK( aLhs != NULL && aRhs != NULL, false );

            return *aLhs < *aRhs;
        }
    };

    int operator-( const SCH_SHEET& aRhs ) const;

    wxPoint GetPosition() const { return m_pos; }

    void SetPosition( const wxPoint& aPosition );

    bool HitTest( const wxPoint& aPosition, int aAccuracy ) const;

    bool HitTest( const EDA_RECT& aRect, bool aContained = false, int aAccuracy = 0 ) const;

    void Plot( PLOTTER* aPlotter );

    EDA_ITEM* Clone() const;

    /**
     * Function SetPageNumbers
     *
     * sets the page numbers for each sheet by load order.
     *
     * The root sheet is always used to set the page numbers no matter which sheet this
     * function is called.  This function will only have meaning when loading legacy
     * schematics.  The upcoming s-expression schematic file format will allow for user
     * defined page numbers.
     */
    void SetPageNumbers();

    /**
     * Function FindSheetByName
     *
     * searches this #SCH_SHEET and all of it's sub-sheets for a sheet named \a aSheetName.
     *
     * @param aSheetName is the name of the sheet to find.
     * @return a pointer to the sheet named \a aSheetName if found or NULL if not found.
     */
    SCH_SHEET* FindSheetByName( const wxString& aSheetName );

    /**
     * Function GetSheets
     *
     * add the pointers to the #SCH_SHEET and all of it's sub-sheets to \a aSheetList.
     *
     * By default no sorting is performed and the #SCH_SHEET pointers are add to the list
     * in the order they were loaded when the schematic was parse.  When \a aSortByPath is
     * true, the list is sorted using the < operator which sort by path length then path
     * time stamps.  This has the same sorting effect as the old SCH_SHEET_PATH::Cmp()
     * function.
     *
     * @param aSheetList is a reference to a set containing the #SCH_SHEET pointers.
     * @param aSortByPath true to sort by path.  False for load order.
     * @return the number of #SCH_SHEET object pointers in \a aSheetList.
     */
    unsigned GetSheets( std::vector< const SCH_SHEET* >& aSheetList,
                        bool aSortByPath = false ) const;

    /**
     * Function GetSheetPaths
     *
     * Returns a list of lists of #SCH_SHEET pointers to \a sSheetPaths.
     *
     * This is analagous to the old SCH_SHEET_LIST::BuildSheetList().  It creates a list of
     * stacks to the sheet pointer hierarchy.
     *
     * @param aSheetPaths is a vector of vector of #SCH_SHEET pointers.
     */
    void GetSheetPaths( std::vector< std::vector< const SCH_SHEET* > >& aSheetPaths ) const;

    /**
     * Function GetRootSheet
     *
     * returns the root sheet of this SCH_SHEET object.
     *
     * The root (top level) sheet can be found by walking up the parent links until the only
     * sheet that has no parent is found.  The root sheet can be found from any sheet in the
     * hierarchy.
     *
     * @return a SCH_SHEET pointer to the root sheet.
     */
    const SCH_SHEET* GetRootSheet() const;

    SCH_SHEET* GetRootSheet()
    {
        return const_cast< SCH_SHEET* >( static_cast< const SCH_SHEET&>( *this ).GetRootSheet() );
    }

    /**
     * Function IsRootSheet
     *
     * returns true if `this` sheet has no parent which indicates it is the root (top level)
     * sheet.
     *
     * @return true if this is the root sheet, otherwise false.
     */
    bool IsRootSheet() const { return GetParent() == NULL; }

    /**
     * Function GetPath
     *
     * recurses up the parent branch up to the root sheet adding a pointer for each
     * parent sheet to \a aSheetPath.
     *
     * @param aSheetPath is a refernce to an #SCH_SHEET object to populate.
     */
    void GetPath( std::vector< const SCH_SHEET* >& aSheetPath ) const;

    /**
     * Function GetPath
     *
     * returns a wxString containing the sheet path of this SCH_SHEET.
     *
     * The SCH_SHEET path is a Posix like path containing the hexadecimal time stamps in
     * the parent order of this SCH_SHEET.  It looks something like /4567FEDC/AA2233DD/.
     */
    wxString GetPath() const;

    /**
     * Function GetHumanReadablePath
     *
     * returns a wxString containing the human readable path of this sheet.
     *
     * Human readable SCH_SHEET paths are Posix like paths made up of the sheet names
     * in the parent order of this SCH_SHEET.  It looks something like /sheet1/sheet2.
     */
    wxString GetHumanReadablePath() const;

    void ClearAnnotation( bool aIncludeSubSheets = false );

    /**
     * Function IsModified
     * checks the sheet and any of it's sub-sheets (hierarchy) for any modifications.
     * @return true if the hierarchy is modified otherwise false.
     */
    bool IsModified() const;

    /**
     * Function ClearModifyStatus
     *
     * clears the modification flag for everything in the sheet and all sub-sheets.
     */
    void ClearModifyStatus();

    /**
     * Function IsAutoSaveRequired
     * checks the entire hierarchy for any modifications that require auto save.
     * @return True if the hierarchy is modified otherwise false.
     */
    bool IsAutoSaveRequired();

    /**
     * Function AnnotatePowerSymbols
     * annotates the power symbols only starting at \a aReference in the sheet path.
     * @param aLibs the library list to use
     * @param aReference A pointer to the number for the reference designator of the
     *                   first power symbol to be annotated.  If the pointer is NULL
     *                   the annotation starts at 1.  The number is incremented for
     *                   each power symbol in the sheet that is annotated.
     */
    void AnnotatePowerSymbols( PART_LIBS* aLibs, int* aReference );

    /**
     * Function UpdateAllScreenReferences
     * updates the reference and the m_Multi parameter (part selection) for all
     * components on a screen depending on the actual sheet.
     * Mandatory in complex hierarchies because sheets use the same screen
     * (basic schematic)
     * but with different references and part selections according to the
     * displayed sheet
     */
    void UpdateAllScreenReferences();

    /**
     * Function GetComponents
     * adds a SCH_REFERENCE() object to \a aReferences for each component in the sheet.
     *
     * @param aLibs the library list to use
     * @param aReferences List of references to populate.
     * @param aIncludePowerSymbols : false to only get normal components.
     * @param aIncludeSubSheets true includes components of all sub-sheets and false includes
     *                          only the components in this sheet.
     */
    void GetComponents( PART_LIBS* aLibs, SCH_REFERENCE_LIST& aReferences,
                        bool aIncludePowerSymbols = true, bool aIncludeSubSheets = true );

    /**
     * Function GetMultiUnitComponents
     * adds a SCH_REFERENCE_LIST object to \a aRefList for each component with multiple units
     * that has the same reference designator for this sheet and all of it's sub-sheets. The
     * map key for each element will be the reference designator.
     *
     * @param aLibs a pointer to the #PART_LIB to use.
     * @param aRefList Map of reference designators to reference lists
     * @param aIncludePowerSymbols : false to only get normal components.
     */
    void GetMultiUnitComponents( PART_LIBS* aLibs, SCH_MULTI_UNIT_REFERENCE_MAP& aRefList,
                                 bool aIncludePowerSymbols = true );

    /**
     * Function IsComplexHierarchy
     * searches all of the sheets for duplicate files names which indicates a complex
     * hierarchy.
     *
     * Typically this function would be called from the root sheet.  However, it is possible
     * to test only the sub-hierarchy from any #SCH_SHEET object.
     *
     * @return true if the #SCH_SHEET is a complex hierarchy.
     */
    bool IsComplexHierarchy() const;

    /**
     * Find the next schematic item in this sheet object.
     *
     * @param aType - The type of schematic item object to search for.
     * @param aLastItem - Start search from aLastItem.  If no aLastItem, search from
     *                    the beginning of the list.
     * @param aWrap - Wrap around the end of the list to find the next item if aLastItem
     *                is defined.
     * @return - The next schematic item if found.  Otherwise, NULL is returned.
     */
    SCH_ITEM* FindNextItem( KICAD_T aType, SCH_ITEM* aLastItem = NULL, bool aWrap = false ) const;

    /**
     * Function TestForRecursion
     *
     * test every SCH_SHEET in the SCH_SHEET hierarchy to verify if adding the sheets stored
     * in \a aSrcSheetHierarchy to the sheet stored in \a aDestFileName  will cause recursion.
     *
     * @param aSrcSheetHierarchy is a list #SCH_SHEET pointer lists of the source sheet add
     *                           to \a aDestFileName.
     * @param aDestFileName is the file name of the destination sheet for \a aSrcFileName.
     * @return true if \a aFileName will cause recursion in the sheet path.  Otherwise false.
     */
    bool TestForRecursion( std::vector< std::vector< const SCH_SHEET* > >& aSrcSheetHierarchy,
                           const wxString& aDestFileName ) const;

#if defined(DEBUG)
    void Show( int nestLevel, std::ostream& os ) const;     // override
#endif

protected:

    /**
     * Renumber the sheet pins in the sheet.
     *
     * This method is used internally by SCH_SHEET to update the pin numbering
     * when the pin list changes.  Make sure you call this method any time a
     * sheet pin is added or removed.
     */
    void renumberPins();
};


#endif /* SCH_SHEEET_H */