Search in sources :

Example 6 with RGallery

use of com.cpjd.roblu.models.metrics.RGallery in project Roblu by wdavies973.

the class PredefinedFormSelector method processForm.

/**
 * Converst the form into an RForm reference
 * @param name the file name
 * @return an RForm instance
 */
private RForm processForm(int index, String name) {
    RForm form = new RForm(null, null);
    ArrayList<RMetric> metrics = new ArrayList<>();
    try {
        AssetManager am = getAssets();
        InputStream is = am.open("predefinedForms" + File.separator + name);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        int ID = 0;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("Title")) {
                items[index] = line.split(":")[1];
                continue;
            } else if (line.startsWith("Description")) {
                sub_items[index] = line.split(":")[1];
                continue;
            }
            switch(line) {
                case "PIT":
                    continue;
                case "MATCH":
                    form.setPit(new ArrayList<>(metrics));
                    metrics.clear();
                    continue;
                case "DEFAULTS":
                    metrics.add(new RTextfield(0, "Team name", false, true, ""));
                    metrics.add(new RTextfield(1, "Team number", true, true, ""));
                    ID = 2;
                    break;
            }
            /*
                 * Process file
                 */
            String regex = "(?<!\\\\)" + Pattern.quote(",");
            String[] tokens = line.split(regex);
            for (int i = 0; i < tokens.length; i++) {
                tokens[i] = tokens[i].replaceAll("\\\\,", ",");
            }
            switch(tokens[0]) {
                case "counter":
                    metrics.add(new RCounter(ID, tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3])));
                    ID++;
                    break;
                case "divider":
                    metrics.add(new RDivider(ID, tokens[1]));
                    ID++;
                    break;
                case "chooser":
                    metrics.add(new RChooser(ID, tokens[1], tokens[2].split(":"), Integer.parseInt(tokens[3])));
                    ID++;
                    break;
                case "slider":
                    metrics.add(new RSlider(ID, tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[4])));
                    ID++;
                    break;
                case "checkbox":
                    LinkedHashMap<String, Boolean> temp = new LinkedHashMap<>();
                    for (String s : tokens[2].split(":")) temp.put(s, false);
                    metrics.add(new RCheckbox(ID, tokens[1], temp));
                    ID++;
                    break;
                case "textfield":
                    metrics.add(new RTextfield(ID, tokens[1], ""));
                    ID++;
                    break;
                case "stopwatch":
                    metrics.add(new RStopwatch(ID, tokens[1], Double.parseDouble(tokens[2])));
                    ID++;
                    break;
                case "boolean":
                    metrics.add(new RBoolean(ID, tokens[1], Boolean.parseBoolean(tokens[2])));
                    ID++;
                    break;
                case "gallery":
                    metrics.add(new RGallery(ID, tokens[1]));
                    ID++;
                    break;
            }
        }
        form.setMatch(metrics);
        Log.d("RBS", "Form created successfully with " + form.getPit().size() + " pit metrics and " + form.getMatch().size() + " match metrics");
        return form;
    } catch (IOException e) {
        Log.d("RBS", "Failed to process form: " + e.getMessage());
        return null;
    }
}
Also used : RDivider(com.cpjd.roblu.models.metrics.RDivider) RBoolean(com.cpjd.roblu.models.metrics.RBoolean) RGallery(com.cpjd.roblu.models.metrics.RGallery) RTextfield(com.cpjd.roblu.models.metrics.RTextfield) ArrayList(java.util.ArrayList) RMetric(com.cpjd.roblu.models.metrics.RMetric) LinkedHashMap(java.util.LinkedHashMap) RForm(com.cpjd.roblu.models.RForm) RCheckbox(com.cpjd.roblu.models.metrics.RCheckbox) RSlider(com.cpjd.roblu.models.metrics.RSlider) RBoolean(com.cpjd.roblu.models.metrics.RBoolean) AssetManager(android.content.res.AssetManager) RChooser(com.cpjd.roblu.models.metrics.RChooser) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException) RStopwatch(com.cpjd.roblu.models.metrics.RStopwatch) BufferedReader(java.io.BufferedReader) RCounter(com.cpjd.roblu.models.metrics.RCounter)

Example 7 with RGallery

use of com.cpjd.roblu.models.metrics.RGallery in project Roblu by wdavies973.

the class ImageGalleryActivity method onActivityResult.

/**
 * Receives the picture that was taken by the user
 * @param requestCode the request code of the child activity
 * @param resultCode the result code of the child activity
 * @param data the picture that was taken
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.GENERAL && resultCode == FragmentActivity.RESULT_OK) {
        // fetch file from storage
        Bitmap bitmap = BitmapFactory.decodeFile(tempPictureFile.getPath());
        // fix rotation
        try {
            ExifInterface ei = new ExifInterface(tempPictureFile.getPath());
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            switch(orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    bitmap = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    bitmap = rotateImage(bitmap, 180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    bitmap = rotateImage(bitmap, 270);
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            Log.d("RBS", "Failed to remove EXIF rotation data from the picture.");
        }
        /*
             * Convert the image into a byte[] and save it to the gallery
             */
        // Convert the bitmap to a byte array
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream);
        byte[] array = stream.toByteArray();
        int newID = new IO(getApplicationContext()).savePicture(eventID, array);
        // Add the image to the current array
        if (IMAGES == null)
            IMAGES = new ArrayList<>();
        IMAGES.add(array);
        // save the ID to the gallery
        for (int i = 0; i < TeamViewer.team.getTabs().get(rTabIndex).getMetrics().size(); i++) {
            if (TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i).getID() == galleryID) {
                if (((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).getPictureIDs() == null) {
                    ((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).setPictureIDs(new ArrayList<Integer>());
                }
                ((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).getPictureIDs().add(newID);
                break;
            }
        }
        TeamViewer.team.setLastEdit(System.currentTimeMillis());
        new IO(getApplicationContext()).saveTeam(eventID, TeamViewer.team);
        imageGalleryAdapter.notifyDataSetChanged();
    } else /*
         * User edited an image
         */
    if (resultCode == Constants.IMAGE_EDITED) {
        TeamViewer.team.setLastEdit(System.currentTimeMillis());
        /*
             * Update the image in the gallery
             */
        for (int i = 0; i < TeamViewer.team.getTabs().get(rTabIndex).getMetrics().size(); i++) {
            if (TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i).getID() == galleryID) {
                if (((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).getPictureIDs() == null) {
                    ((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).setPictureIDs(new ArrayList<Integer>());
                }
                ((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).getPictureIDs().add(new IO(getApplicationContext()).savePicture(eventID, IMAGES.get(data.getIntExtra("position", 0))));
                break;
            }
        }
        new IO(getApplicationContext()).saveTeam(eventID, TeamViewer.team);
        imageGalleryAdapter.notifyDataSetChanged();
    } else /*
         * User deleted an image
         */
    if (resultCode == Constants.IMAGE_DELETED) {
        // Remove the image from the gallery ID list
        for (int i = 0; i < TeamViewer.team.getTabs().get(rTabIndex).getMetrics().size(); i++) {
            if (TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i).getID() == galleryID) {
                int pictureID = ((RGallery) TeamViewer.team.getTabs().get(rTabIndex).getMetrics().get(i)).getPictureIDs().remove(data.getIntExtra("position", 0));
                // delete from file system
                new IO(getApplicationContext()).deletePicture(eventID, pictureID);
                break;
            }
        }
        IMAGES.remove(data.getIntExtra("position", 0));
        imageGalleryAdapter.notifyDataSetChanged();
        TeamViewer.team.setLastEdit(System.currentTimeMillis());
        new IO(getApplicationContext()).saveTeam(eventID, TeamViewer.team);
    }
}
Also used : Bitmap(android.graphics.Bitmap) RGallery(com.cpjd.roblu.models.metrics.RGallery) IO(com.cpjd.roblu.io.IO) ExifInterface(android.media.ExifInterface) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 8 with RGallery

use of com.cpjd.roblu.models.metrics.RGallery in project Roblu by wdavies973.

the class TeamMetricProcessor method process.

/**
 * Processes an RTeam object and sets its filterTag and relevance variables.
 * -filterTag is a string representing a certain metric as defined by param method and param ID
 * -relevance is used for sorting (relevance is assigned differently for the type of RMetric, but for example,
 * counters with the highest value with cause that team to be sorted at the top)
 *
 * @param team the team to process
 * @param method an int from PROCESS_METHOD that defines how an team should be processed
 * @param ID the id of the metric to process, this value will be ignored if method is PIT, PREDICTIONS, or MATCHES
 */
public void process(RTeam team, int method, int ID) {
    team.setCustomRelevance(0);
    /*
         * Helper variables
         */
    StringBuilder rawData = new StringBuilder();
    int occurrences = 0;
    double relevance = 0;
    double average = 0.0, min = 0.0, max = 0.0;
    /*
         * If the request method is PIT or PREDICTIONS, use the following code to
         * sort the team. Note, each team will only have one value that needs to be
         * analyzed, so statistics are essentially invalid
         */
    if (method == PROCESS_METHOD.PIT || method == PROCESS_METHOD.PREDICTIONS) {
        for (RMetric metric : team.getTabs().get(method).getMetrics()) {
            if (metric.getID() != ID)
                continue;
            if (metric instanceof RBoolean) {
                rawData.append("Boolean: ").append(metric.getTitle()).append(" is ").append(friendlyBoolean((RBoolean) metric));
                if (metric.isModified() && ((RBoolean) metric).isValue())
                    relevance++;
            } else if (metric instanceof RCounter) {
                rawData.append("Counter: ").append(metric.getTitle()).append(" is ").append(friendlyCounter((RCounter) metric));
                relevance += ((RCounter) metric).getValue();
            } else if (metric instanceof RSlider) {
                rawData.append("Slider: ").append(metric.getTitle()).append(" is ").append(friendlySlider((RSlider) metric));
                relevance += ((RSlider) metric).getValue();
            } else if (metric instanceof RStopwatch) {
                rawData.append("Stopwatch: ").append(metric.getTitle()).append(" is ").append(friendlyStopwatch((RStopwatch) metric));
                relevance += ((RStopwatch) metric).getTime();
            } else if (metric instanceof RTextfield) {
                rawData.append("Textfield: ").append(metric.getTitle()).append(" has  ").append(((RTextfield) metric).getText().length()).append(" characters");
                relevance += ((RTextfield) metric).getText().length();
            } else if (metric instanceof RGallery) {
                rawData.append("Gallery: ").append(metric.getTitle()).append(" contains  ").append(((RGallery) metric).getImages().size()).append(" images");
                relevance += ((RGallery) metric).getImages().size();
            } else if (metric instanceof RCheckbox) {
                rawData.append("Checkbox: ").append(metric.getTitle()).append(" values:  ").append(friendlyCheckbox((RCheckbox) metric));
                relevance += getCheckedAmount((RCheckbox) metric);
            } else if (metric instanceof RChooser) {
                rawData.append("Chooser: ").append(metric.getTitle()).append(" has value  ").append(((RChooser) metric).getValues()[((RChooser) metric).getSelectedIndex()]);
            }
            rawData.append(" in ").append(friendlyMode(method));
            team.setFilterTag("\n" + rawData.toString());
            team.setCustomRelevance(relevance);
            break;
        }
    } else /*
         * If the request method is MATCHES, then the following code has to be used
         * to look at each particular RTab object within the team object
         */
    if (method == PROCESS_METHOD.MATCHES) {
        if (team.getTabs() == null || team.getTabs().size() == 0) {
            team.setFilterTag("\nThis team does not contain any matches that can be sorted.");
            return;
        }
        /*
             * This nested for loop will go through every team tab and every metric within each team tab.
             * This loop should only process the RAW DATA for each metric, the overview stuff will be added at the end.
             * Use StringBuilder rawData to store raw data
             */
        rawData.append("\nRaw data: ");
        for (int i = 2; i < team.getTabs().size(); i++) {
            for (RMetric metric : team.getTabs().get(i).getMetrics()) {
                // Make sure that the metric that is being processed is equal to the inputted value
                if (metric.getID() != ID)
                    continue;
                // RBoolean type
                if (metric instanceof RBoolean) {
                    RBoolean rBoolean = (RBoolean) metric;
                    // if the value is modified and true, add some relevance info
                    if (rBoolean.isModified() && rBoolean.isValue()) {
                        occurrences++;
                        relevance++;
                    }
                    // add raw data
                    rawData.append(friendlyBoolean((RBoolean) metric)).append(ending(i, team.getTabs()));
                } else // RCounter type
                if (metric instanceof RCounter) {
                    double value = ((RCounter) metric).getValue();
                    if (i == 2)
                        min = value;
                    // Overview stats will only consider modified items
                    if (metric.isModified()) {
                        /*
                             * Progressively calculate the min, max, and average values
                             */
                        if (value < min)
                            min = value;
                        if (value > max)
                            max = value;
                        average += value / (double) numModified(team.getTabs(), ID);
                        relevance = average;
                    }
                    // add raw data
                    rawData.append(friendlyCounter((RCounter) metric)).append(ending(i, team.getTabs()));
                } else if (metric instanceof RCalculation) {
                    try {
                        double value = Double.parseDouble(((RCalculation) metric).getValue(team.getTabs().get(i).getMetrics()));
                        if (i == 2)
                            min = value;
                        // Overview stats will only consider modified items
                        if (metric.isModified()) {
                            /*
                             * Progressively calculate the min, max, and average values
                             */
                            if (value < min)
                                min = value;
                            if (value > max)
                                max = value;
                            average += value / (double) numModified(team.getTabs(), ID);
                            relevance = average;
                        }
                        // add raw data
                        rawData.append(friendlyCounter((RCounter) metric)).append(ending(i, team.getTabs()));
                    } catch (Exception e) {
                    // eat it
                    }
                } else // RSlider type
                if (metric instanceof RSlider) {
                    int value = ((RSlider) metric).getValue();
                    if (i == 2)
                        min = value;
                    // Overview stats will only consider modified sliders
                    if (metric.isModified()) {
                        if (value < min)
                            min = value;
                        if (value > max)
                            max = value;
                        average += (double) value / (double) numModified(team.getTabs(), ID);
                        relevance = average;
                    }
                    // add raw data
                    rawData.append(friendlySlider((RSlider) metric)).append(ending(i, team.getTabs()));
                } else // RStopwatch type
                if (metric instanceof RStopwatch) {
                    double value = ((RStopwatch) metric).getTime();
                    if (i == 2)
                        min = value;
                    // Overview stats will only consider modified stopwatches
                    if (metric.isModified()) {
                        /*
                             * Progressively calculate the min, max, and average values
                             */
                        if (value < min)
                            min = value;
                        if (value > max)
                            max = value;
                        average += value / (double) numModified(team.getTabs(), ID);
                        relevance = average;
                    }
                    // add raw data
                    rawData.append(friendlyStopwatch((RStopwatch) metric)).append(ending(i, team.getTabs()));
                } else // RTextfield type
                if (metric instanceof RTextfield) {
                    int value = ((RTextfield) metric).getText().length();
                    // Overview stats will only consider modified textfields
                    if (metric.isModified()) {
                        /*
                             * Progressively calculate the min, max, and average values
                             */
                        if (value < min)
                            min = value;
                        if (value > max)
                            max = value;
                        average += (double) value / (double) numModified(team.getTabs(), ID);
                        relevance = average;
                    }
                    // add raw data
                    rawData.append(value).append(" chars").append(ending(i, team.getTabs()));
                } else // RGallery type
                if (metric instanceof RGallery) {
                    int value = ((RGallery) metric).getImages().size();
                    // Overview stats will only consider modified textfields
                    if (metric.isModified()) {
                        /*
                             * Progressively calculate the min, max, and average values
                             */
                        if (value < min)
                            min = value;
                        if (value > max)
                            max = value;
                        average += (double) value / (double) numModified(team.getTabs(), ID);
                        relevance = average;
                    }
                    // add raw data
                    rawData.append(value).append(" images ").append(ending(i, team.getTabs()));
                } else // RCheckbox type
                if (metric instanceof RCheckbox) {
                    // add raw data
                    rawData.append(friendlyCheckbox((RCheckbox) metric)).append(ending(i, team.getTabs()));
                    relevance += getCheckedAmount((RCheckbox) metric);
                } else // RChooser type
                if (metric instanceof RChooser) {
                    if (metric.isModified())
                        relevance++;
                    // add raw data
                    rawData.append(((RChooser) metric).getValues()[((RChooser) metric).getSelectedIndex()]).append(ending(i, team.getTabs()));
                } else // Field data
                if (metric instanceof RFieldData) {
                    // Find the sub metric
                    if (((RFieldData) metric).getData() != null && ((RFieldData) metric).getData().get(inMatchTitle) != null)
                        rawData.append(((RFieldData) metric).getData().get(inMatchTitle).get(team.getTabs().get(i).isRedAlliance() ? 0 : 1).toString()).append(ending(i, team.getTabs()));
                    // Overview stats will only consider modified textfields
                    if (metric.isModified()) {
                        /*
                             * Progressively calculate the min, max, and average values
                             */
                        try {
                            double value = Double.parseDouble(((RFieldData) metric).getData().get(inMatchTitle).get(team.getTabs().get(i).isRedAlliance() ? 0 : 1).toString());
                            if (i == 2)
                                min = value;
                            if (value < min)
                                min = value;
                            if (value > max)
                                max = value;
                            average += value / (double) numModified(team.getTabs(), ID);
                            relevance = average;
                        } catch (Exception e) {
                        // eat it
                        }
                    }
                }
                /*
                     * Now, add the overview statistics to the team if the metric has overview statistics
                     * available
                    */
                max = Utils.round(max, 2);
                min = Utils.round(min, 2);
                average = Utils.round(average, 2);
                StringBuilder overview = new StringBuilder();
                if (metric instanceof RBoolean)
                    overview.append("Boolean: ").append(metric.getTitle()).append(" is true in ").append(occurrences).append(" / ").append(team.getTabs().size() - 2).append(" matches");
                else if (metric instanceof RCounter)
                    overview.append("Counter: ").append(metric.getTitle()).append(" Average: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RCalculation)
                    overview.append("Calculation: ").append(metric.getTitle()).append(" Average: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RSlider)
                    overview.append("Slider: ").append(metric.getTitle()).append(" Average: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RStopwatch)
                    overview.append("Stopwatch: ").append(metric.getTitle()).append(" Average: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RTextfield)
                    overview.append("Textfield: ").append(metric.getTitle()).append(" Average chars: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RGallery)
                    overview.append("Gallery: ").append(metric.getTitle()).append(" Average images: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                else if (metric instanceof RChooser)
                    overview.append("Chooser: ").append(metric.getTitle());
                else if (metric instanceof RCheckbox)
                    overview.append("Checkbox: ").append(metric.getTitle());
                else if (metric instanceof RFieldData) {
                    overview.append("Field data: ").append(inMatchTitle);
                    try {
                        // this will fail if the value isn't a number
                        if (average != 0 || min != 0 || max != 0)
                            overview.append("\nAverage: ").append(Utils.round(average, 2)).append(" Min: ").append(min).append(" Max: ").append(max);
                    } catch (Exception e) {
                    // eat it
                    }
                }
                /*
                     * Now append the raw data as processed above
                     */
                team.setFilterTag("\n" + overview.append(rawData).toString());
                team.setCustomRelevance(relevance);
                // exit the loop, the metric has been fully processed
                break;
            }
        }
    } else /*
         * The user requested MATCH_WINS
         */
    if (method == PROCESS_METHOD.OTHER && ID == PROCESS_METHOD.OTHER_METHOD.MATCH_WINS) {
        for (int i = 2; i < team.getTabs().size(); i++) {
            if (team.getTabs().get(i).isWon()) {
                occurrences++;
                relevance++;
                rawData.append("W");
            } else
                rawData.append("L");
            rawData.append(ending(i, team.getTabs()));
        }
        /*
             * Setup overview rawData and add raw data
             */
        team.setCustomRelevance(relevance);
        team.setFilterTag("\n" + String.valueOf(occurrences) + " match wins\n" + rawData.toString());
    } else /*
         * The user requested IN_MATCH
         */
    if (method == PROCESS_METHOD.OTHER && ID == PROCESS_METHOD.OTHER_METHOD.IN_MATCH) {
        team.setFilter(TeamsView.SORT_TYPE.NUMERICAL);
        for (int i = 2; i < team.getTabs().size(); i++) {
            if (team.getTabs().get(i).getTitle().equalsIgnoreCase(inMatchTitle)) {
                team.setFilterTag("\n" + rawData.append("In ").append(inMatchTitle).toString());
                team.setCustomRelevance(1);
            }
        }
    } else /*
         * The user request a reset
         */
    if (method == PROCESS_METHOD.OTHER && ID == PROCESS_METHOD.OTHER_METHOD.RESET) {
        team.setFilterTag("");
        team.setCustomRelevance(0);
    }
}
Also used : RBoolean(com.cpjd.roblu.models.metrics.RBoolean) RChooser(com.cpjd.roblu.models.metrics.RChooser) RGallery(com.cpjd.roblu.models.metrics.RGallery) RTextfield(com.cpjd.roblu.models.metrics.RTextfield) RFieldData(com.cpjd.roblu.models.metrics.RFieldData) RMetric(com.cpjd.roblu.models.metrics.RMetric) RCalculation(com.cpjd.roblu.models.metrics.RCalculation) RStopwatch(com.cpjd.roblu.models.metrics.RStopwatch) RCheckbox(com.cpjd.roblu.models.metrics.RCheckbox) RSlider(com.cpjd.roblu.models.metrics.RSlider) RCounter(com.cpjd.roblu.models.metrics.RCounter)

Example 9 with RGallery

use of com.cpjd.roblu.models.metrics.RGallery in project Roblu by wdavies973.

the class EventCreateMethodPicker method onActivityResult.

/**
 * Receives result data from child activities
 * @param requestCode the request code of the child activities
 * @param resultCode the result code of the child activity
 * @param data any result data returned from the activity
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    /*
         * The user selected a backup file, let's attempt to import it here
         */
    if (requestCode == Constants.FILE_CHOOSER) {
        // this means the user didn't select a file, no point in returning an error message
        if (data == null)
            return;
        try {
            IO io = new IO(getApplicationContext());
            RBackup backup = io.convertBackupFile(data.getData());
            if (!backup.getFileVersion().equals(IO.PREFIX)) {
                Utils.showSnackbar(findViewById(R.id.activity_create_event_picker), getApplicationContext(), "Invalid backup file. Backup was created with an older version of Roblu.", true, rui.getPrimaryColor());
                return;
            }
            /*
                 * Create the event, we're not gonna use an AsyncTask because the user is just
                 * watching the event import anyway, and it will only freeze the UI for a couple hundred
                 * milliseconds.
                 */
            REvent event = backup.getEvent();
            event.setCloudEnabled(false);
            event.setID(io.getNewEventID());
            io.saveEvent(event);
            io.saveForm(event.getID(), backup.getForm());
            if (backup.getTeams() != null) {
                for (RTeam team : backup.getTeams()) {
                    for (RTab tab : team.getTabs()) {
                        for (RMetric metric : tab.getMetrics()) {
                            if (metric instanceof RGallery && ((RGallery) metric).getImages() != null) {
                                // Add images to the current gallery
                                for (int i = 0; i < ((RGallery) metric).getImages().size(); i++) {
                                    ((RGallery) metric).getPictureIDs().add(io.savePicture(event.getID(), ((RGallery) metric).getImages().get(i)));
                                }
                                ((RGallery) metric).setImages(null);
                            }
                        }
                    }
                    io.saveTeam(event.getID(), team);
                }
            }
            Utils.showSnackbar(findViewById(R.id.activity_create_event_picker), getApplicationContext(), "Successfully imported event from backup", false, rui.getPrimaryColor());
            Intent intent = new Intent();
            intent.putExtra("eventID", event.getID());
            setResult(Constants.NEW_EVENT_CREATED, intent);
            finish();
        } catch (Exception e) {
            Utils.showSnackbar(findViewById(R.id.activity_create_event_picker), getApplicationContext(), "Invalid backup file", true, rui.getPrimaryColor());
        }
    } else /*
         * The user created an event manually with EventEditor, we actually don't need to do anything but auto-finish our class
         * with a result code letting the TeamsView class now to refresh the event list
         */
    if (resultCode == Constants.NEW_EVENT_CREATED) {
        Bundle b = data.getExtras();
        Intent intent = new Intent();
        if (b != null)
            intent.putExtras(b);
        setResult(Constants.NEW_EVENT_CREATED, intent);
        finish();
    }
}
Also used : RBackup(com.cpjd.roblu.models.RBackup) RTeam(com.cpjd.roblu.models.RTeam) RTab(com.cpjd.roblu.models.RTab) RGallery(com.cpjd.roblu.models.metrics.RGallery) IO(com.cpjd.roblu.io.IO) Bundle(android.os.Bundle) REvent(com.cpjd.roblu.models.REvent) Intent(android.content.Intent) RMetric(com.cpjd.roblu.models.metrics.RMetric)

Example 10 with RGallery

use of com.cpjd.roblu.models.metrics.RGallery in project Roblu by wdavies973.

the class InitPacker method doInBackground.

@Override
protected Boolean doInBackground(Void... params) {
    /*
         * Make sure this thread has network permissions
         */
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
    StrictMode.setThreadPolicy(policy);
    Log.d("RBS", "Executing InitPacker task...");
    IO io = ioWeakReference.get();
    RSettings settings = io.loadSettings();
    RSyncSettings cloudSettings = io.loadCloudSettings();
    cloudSettings.setPurgeRequested(false);
    io.saveCloudSettings(cloudSettings);
    io.saveSettings(settings);
    Request r = new Request(settings.getServerIP());
    if (!r.ping()) {
        listener.statusUpdate("It appears as though the server is offline. Try again later.");
        return false;
    }
    /*
         * Load all teams from the event, also make sure that that the teams are verified
         */
    REvent event = io.loadEvent(eventID);
    event.setReadOnlyTeamNumber(-1);
    RForm form = io.loadForm(eventID);
    RTeam[] teams = io.loadTeams(eventID);
    if (event == null || form == null || teams == null || teams.length == 0) {
        Log.d("RBS", "Not enough data to warrant an event upload.");
        listener.statusUpdate("This event doesn't contain any teams or sufficient data to upload to the server. Create some teams!");
        return false;
    }
    // Generate the checkouts
    SyncHelper syncHelper = new SyncHelper(io, event, SyncHelper.MODES.NETWORK);
    ArrayList<RCheckout> checkouts = syncHelper.generateCheckoutsFromEvent(teams, -1);
    // Remove field data
    try {
        for (RCheckout checkout : checkouts) {
            for (RTab tab : checkout.getTeam().getTabs()) {
                for (RMetric metric : tab.getMetrics()) {
                    if (metric instanceof RFieldData) {
                        ((RFieldData) metric).setData(null);
                    }
                }
            }
        }
    } catch (Exception e) {
    // Doesn't matter
    }
    /*
         * Convert into JSON and upload
         */
    ObjectMapper mapper = new ObjectMapper();
    try {
        // serialization all the checkouts and pack them in an json array, this will be processed by the server
        String serializedCheckouts = syncHelper.packCheckouts(checkouts);
        String serializedForm = mapper.writeValueAsString(form);
        String serializedUI = mapper.writeValueAsString(settings.getRui());
        String eventName = event.getName();
        if (eventName == null)
            eventName = "";
        if (event.getKey() == null)
            event.setKey("");
        CloudCheckoutRequest ccr = new CloudCheckoutRequest(r, settings.getCode());
        Log.d("RBS", "Initializing init packer upload...");
        boolean success = ccr.init(settings.getTeamNumber(), eventName, serializedForm, serializedUI, serializedCheckouts, event.getKey());
        /*
             * Disable all other events with cloud syncing enabled
             */
        if (success) {
            REvent[] events = io.loadEvents();
            for (int i = 0; events != null && i < events.length; i++) {
                events[i].setCloudEnabled(events[i].getID() == eventID);
                io.saveEvent(events[i]);
            }
            cloudSettings.getCheckoutSyncIDs().clear();
            /*
                 * Add default sync ids
                 */
            for (RCheckout checkout : checkouts) {
                cloudSettings.getCheckoutSyncIDs().put(checkout.getID(), 0L);
            }
            io.saveCloudSettings(cloudSettings);
            io.saveSettings(settings);
        } else
            listener.statusUpdate("An error occurred. Event was not uploaded.");
        return success;
    } catch (Exception e) {
        Log.d("RBS", "An error occurred in InitPacker: " + e.getMessage());
        listener.statusUpdate("An error occurred. Event was not uploaded.");
        return false;
    } finally {
        /*
             * Set all images to null to return memory to normal
             */
        for (RCheckout checkout : checkouts) {
            for (RTab tab : checkout.getTeam().getTabs()) {
                for (RMetric metric : tab.getMetrics()) {
                    if (metric instanceof RGallery) {
                        ((RGallery) metric).setImages(null);
                    }
                }
            }
        }
    }
}
Also used : RTab(com.cpjd.roblu.models.RTab) RGallery(com.cpjd.roblu.models.metrics.RGallery) RFieldData(com.cpjd.roblu.models.metrics.RFieldData) RMetric(com.cpjd.roblu.models.metrics.RMetric) StrictMode(android.os.StrictMode) RForm(com.cpjd.roblu.models.RForm) REvent(com.cpjd.roblu.models.REvent) SyncHelper(com.cpjd.roblu.sync.SyncHelper) RCheckout(com.cpjd.roblu.models.RCheckout) RSyncSettings(com.cpjd.roblu.models.RSyncSettings) RSettings(com.cpjd.roblu.models.RSettings) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest) RTeam(com.cpjd.roblu.models.RTeam) IO(com.cpjd.roblu.io.IO) Request(com.cpjd.http.Request) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest)

Aggregations

RGallery (com.cpjd.roblu.models.metrics.RGallery)12 RMetric (com.cpjd.roblu.models.metrics.RMetric)9 RTab (com.cpjd.roblu.models.RTab)6 RTeam (com.cpjd.roblu.models.RTeam)6 ArrayList (java.util.ArrayList)6 RBoolean (com.cpjd.roblu.models.metrics.RBoolean)5 RCalculation (com.cpjd.roblu.models.metrics.RCalculation)5 RCheckbox (com.cpjd.roblu.models.metrics.RCheckbox)5 RChooser (com.cpjd.roblu.models.metrics.RChooser)5 RCounter (com.cpjd.roblu.models.metrics.RCounter)5 RFieldData (com.cpjd.roblu.models.metrics.RFieldData)5 RSlider (com.cpjd.roblu.models.metrics.RSlider)5 RStopwatch (com.cpjd.roblu.models.metrics.RStopwatch)5 IO (com.cpjd.roblu.io.IO)4 REvent (com.cpjd.roblu.models.REvent)4 RForm (com.cpjd.roblu.models.RForm)4 RDivider (com.cpjd.roblu.models.metrics.RDivider)4 RTextfield (com.cpjd.roblu.models.metrics.RTextfield)4 IOException (java.io.IOException)3 Bitmap (android.graphics.Bitmap)2