/* (non-Javadoc)
   * @see com.kp.marsh.ebt.server.importer.dao.impl.ImportController#listOffices()
   */
  @Override
  public List<MarshOffice> listOffices() {
    List<MarshOffice> result = new ArrayList<MarshOffice>();
    Session session = (Session) this.connection.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    try {
      Query query = session.createQuery("from MOffCeAccounts");

      List<MOffCeAccounts> collections = query.list();

      Map<String, MarshOffice> officesMap = new HashMap<String, MarshOffice>();

      for (MOffCeAccounts mOffCeAccounts : collections) {

        // check if the office already exists
        MarshOffice office = officesMap.get(mOffCeAccounts.getCodiceUfficio());
        if (null == office || StringUtils.isEmpty(mOffCeAccounts.getCodiceUfficio())) {
          office = new MarshOffice();
          officesMap.put(mOffCeAccounts.getCodiceUfficio(), office);
          office.setEysCode(mOffCeAccounts.getCodiceUfficio());
          office.setOfficeName(mOffCeAccounts.getNomeUfficio());
          result.add(office);
          if (StringUtils.isEmpty(office.getEysCode()))
            log.error(office.getOfficeName() + " eys code: " + office.getEysCode());
        }

        if (office != null) {
          MarshCE mCE = office.getMarshCEMap().get(mOffCeAccounts.getCodiceEurosys());
          if (null == mCE && StringUtils.isNotEmpty(mOffCeAccounts.getAdUsername())) {
            mCE = new MarshCE();
            office.getMarshCEMap().put(mOffCeAccounts.getCodiceEurosys(), mCE);
            mCE.setEysCode(mOffCeAccounts.getCodiceEurosys());
            mCE.setNominativo(mOffCeAccounts.getNomeIdentificativo());
            mCE.setUsername(mOffCeAccounts.getAdUsername());
            if (StringUtils.isEmpty(mCE.getEysCode()))
              log.debug("\t" + mCE.getNominativo() + " eys code: " + mCE.getEysCode());
          }
        }
      }

      tx.commit();
    } catch (HibernateException ex) {
      log.error("Exception in listOffices", ex);
      ex.printStackTrace();
      tx.rollback();
    } finally {
      session.close();
    }

    return result;
  }