/* (non-Javadoc)
   * @see sif3.common.interfaces.Provider#createMany(java.lang.Object, sif3.common.model.SIFZone, sif3.common.model.SIFContext)
   */
  @Override
  public List<CreateOperationStatus> createMany(
      Object data,
      boolean useAdvisory,
      SIFZone zone,
      SIFContext context,
      RequestMetadata metadata,
      ResponseParameters customResponseParams)
      throws IllegalArgumentException, PersistenceException {
    // Must be of type StudentPersonalType
    if (data instanceof StudentPersonalCollectionType) {
      logger.debug(
          "Create students (Bulk Operation) for "
              + getZoneAndContext(zone, context)
              + " and RequestMetadata = "
              + metadata);
      StudentPersonalCollectionType students = (StudentPersonalCollectionType) data;
      ArrayList<CreateOperationStatus> opStatus = new ArrayList<CreateOperationStatus>();
      int i = 0;
      for (StudentPersonalType student : students.getStudentPersonal()) {
        if ((i % 3) == 0) {
          // Set advisoryID the same as resourceID.
          opStatus.add(
              new CreateOperationStatus(
                  student.getRefId(),
                  student.getRefId(),
                  404,
                  new ErrorDetails(400, "Data not good.")));
        } else {
          if (useAdvisory) {
            // Advisory refId was used. Set resourceId and advisoryId to the same
            opStatus.add(new CreateOperationStatus(student.getRefId(), student.getRefId(), 201));
          } else {
            // Create a new refId (resourceID) but we must also report back the original RefId as
            // the advisory if it was available.
            opStatus.add(
                new CreateOperationStatus(
                    UUIDGenerator.getSIF2GUIDUpperCase(), student.getRefId(), 201));
          }
        }
        i++;
      }

      return opStatus;
    } else {
      throw new IllegalArgumentException(
          "Expected Object Type  = StudentCollectionType. Received Object Type = "
              + data.getClass().getSimpleName());
    }
  }
  /* (non-Javadoc)
   * @see sif3.common.interfaces.Provider#updateMany(java.lang.Object, sif3.common.model.SIFZone, sif3.common.model.SIFContext)
   */
  @Override
  public List<OperationStatus> updateMany(
      Object data,
      SIFZone zone,
      SIFContext context,
      RequestMetadata metadata,
      ResponseParameters customResponseParams)
      throws IllegalArgumentException, PersistenceException {
    // Must be of type StudentPersonalType
    if (data instanceof StudentPersonalCollectionType) {
      logger.debug(
          "Update students (Bulk Operation) for "
              + getZoneAndContext(zone, context)
              + " and RequestMetadata = "
              + metadata);
      StudentPersonalCollectionType students = (StudentPersonalCollectionType) data;
      ArrayList<OperationStatus> opStatus = new ArrayList<OperationStatus>();
      int i = 0;
      for (StudentPersonalType student : students.getStudentPersonal()) {
        if ((i % 3) == 0) {
          opStatus.add(
              new OperationStatus(
                  student.getRefId(),
                  404,
                  new ErrorDetails(
                      404, "Student with GUID = " + student.getRefId() + " does not exist.")));
        } else {
          opStatus.add(new OperationStatus(student.getRefId(), 200));
        }
        i++;
      }

      return opStatus;
    } else {
      throw new IllegalArgumentException(
          "Expected Object Type  = StudentCollectionType. Received Object Type = "
              + data.getClass().getSimpleName());
    }
  }
  /* (non-Javadoc)
   * @see sif3.common.interfaces.Provider#createSingle(java.lang.Object, sif3.common.model.SIFZone, sif3.common.model.SIFContext)
   */
  @Override
  public Object createSingle(
      Object data,
      boolean useAdvisory,
      SIFZone zone,
      SIFContext context,
      RequestMetadata metadata,
      ResponseParameters customResponseParams)
      throws IllegalArgumentException, PersistenceException {
    logger.debug(
        "Create Single Student for "
            + getZoneAndContext(zone, context)
            + " and RequestMetadata = "
            + metadata);

    //    	return null; // test return null value

    // Must be of type StudentPersonalType
    if (data instanceof StudentPersonalType) {
      StudentPersonalType student = (StudentPersonalType) data;
      if (StringUtils.isEmpty(student.getRefId())) {
        // In future this should be a UUID instead of a GUID
        if (!useAdvisory) {
          // Create new UUID because the advisory shall not be used.
          student.setRefId(UUIDGenerator.getSIF2GUIDUpperCase());
        }
        // else leave student UUID untouched.
      }

      // In the real implementation we would call a BL method here to create the Student.
      return student;
    } else {
      throw new IllegalArgumentException(
          "Expected Object Type  = StudentPersonalType. Received Object Type = "
              + data.getClass().getSimpleName());
    }
  }
  public StudentPersonalProvider() {
    super();

    logger.debug("Constructor for StudentPersonalProvider has been called.");
    if (students == null) {
      logger.debug(
          "Constructor for StudentPersonalProvider called for the first time. Try to load students from XML file...");

      // Load all students so that we can do some real stuff here.
      String studentFile =
          getServiceProperties().getPropertyAsString("provider.student.file.location", null);
      if (studentFile != null) {
        //				String inputXML = FileReaderWriter.getFileContent(studentFile,
        // getProviderEnvironment().getCharsetEncoding());
        String inputXML = FileReaderWriter.getFileContent(studentFile, ModelObjectConstants.UTF_8);
        try {
          StudentPersonalCollectionType studentList =
              (StudentPersonalCollectionType)
                  getUnmarshaller()
                      .unmarshalFromXML(inputXML, getMultiObjectClassInfo().getObjectType());
          if ((studentList != null) && (studentList.getStudentPersonal() != null)) {
            students = new HashMap<String, StudentPersonalType>();
            for (StudentPersonalType studentPersonal : studentList.getStudentPersonal()) {
              //							studentPersonal.setRefId(UUIDGenerator.getUUID());
              students.put(studentPersonal.getRefId(), studentPersonal);
            }
            logger.debug("Loaded " + students.size() + " Students into memory.");
          }
        } catch (UnmarshalException ex) {
          ex.printStackTrace();
        } catch (UnsupportedMediaTypeException ex) {
          ex.printStackTrace();
        }
      }
    }

    if (teachingGroupStudents == null) {
      logger.debug("Try to load students for teaching group from XML file...");

      // Load all students so that we can do some real stuff here.
      String fileName =
          getServiceProperties().getPropertyAsString("provider.teachinggroup.file.location", null);
      if (fileName != null) {
        String inputXML = FileReaderWriter.getFileContent(fileName, ModelObjectConstants.UTF_8);
        try {
          TeachingGroupCollectionType classes =
              (TeachingGroupCollectionType)
                  getUnmarshaller()
                      .unmarshalFromXML(
                          inputXML, ModelObjectConstants.TEACHING_GROUPS.getObjectType());
          if ((classes != null) && (classes.getTeachingGroup() != null)) {
            // Get student list of first teaching group
            JAXBElement<StudentList> jaxbClassStudents =
                classes.getTeachingGroup().get(0).getStudentList();
            if (jaxbClassStudents != null) {
              teachingGroupStudents = new HashMap<String, StudentPersonalType>();
              StudentList classStudents = jaxbClassStudents.getValue();
              for (TeachingGroupStudent student : classStudents.getTeachingGroupStudent()) {
                teachingGroupStudents.put(
                    student.getStudentPersonalRefId().getValue(),
                    students.get(student.getStudentPersonalRefId().getValue()));
              }
            }
            logger.debug(
                "Loaded "
                    + teachingGroupStudents.size()
                    + " teaching group students for a class into memory.");
          }
        } catch (UnmarshalException ex) {
          ex.printStackTrace();
        } catch (UnsupportedMediaTypeException ex) {
          ex.printStackTrace();
        }
      }
    }

    // If students are still null then something must have failed and would have been logged.
    // For the purpose of making things work ok we initialise the students hashmap now. It will
    // avoid null pointer errors.
    if (students == null) {
      students = new HashMap<String, StudentPersonalType>();
    }
    if (teachingGroupStudents == null) {
      teachingGroupStudents = new HashMap<String, StudentPersonalType>();
    }
  }