<commit_before>/*
 * Copyright 2016 <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

angular.module('symphonia.services')
  .factory('ImageLoadService', function ($q, $log, $cordovaCamera, $cordovaDevice) {
    var imageFileUri = '';
    var filenameWithExtension = '';
    var base64Data = '';
    var mime = 'image/*';

    function getPicture(sourceType) {
      var options = {
        destinationType: Camera.DestinationType.FILE_URI,
        mediaType: Camera.MediaType.PICTURE,
        sourceType: sourceType,
        saveToPhoroAlbum: sourceType === Camera.PictureSourceType.CAMERA
      };

      return $cordovaCamera.getPicture(options).then(function (newUri) {
        switch ($cordovaDevice.getPlatform()) {
          case 'iOS':
            return isIos(newUri);
          case 'Android':
            return isAndroid(newUri);
          default:
            return $q.reject('');
        }
      }, function (error) {
        if (error.toUpperCase() === 'Selection cancelled.'.toUpperCase() ||
          error.toUpperCase() === 'Camera cancelled.'.toUpperCase() ||
          error.toUpperCase() === 'no image selected'.toUpperCase()) {
          // When cancelled by user, we do not want to show error dialog.
          // FIXME: maybe there is some another error message when camera cancelled on iOS.
          // #wontfix until there is a opportunity to try on the real iOS device (not just simulator)
          return $q.when();
        }
        $log.error('Failed to pick a photo: ' + error);
        return $q.reject('Error while processing a picture.');
      });
    }

    function isIos(uri) {
      return getCorrectFileUriAndBase64Data(uri).then(function (uriAndRawBase64) {
        base64Data = uriAndRawBase64.base64;
        imageFileUri = uriAndRawBase64.uri;
        return $q.when();
      }, function (message) {
        return $q.reject(message);
      });
    }

    function isAndroid(uri) {
      var deferred = $q.defer();

      $log.debug('URI before edition:' + uri);
      window.FilePath.resolveNativePath(uri, function (correctUri) {
        // FIXME newest security update will probably crash this workaround
        $log.debug('URI after edition' + correctUri);
        getCorrectFileUriAndBase64Data(correctUri).then(function (uriAndRawBase64) {
          base64Data = uriAndRawBase64.base64;
          imageFileUri = uriAndRawBase64.uri;
          deferred.resolve();
        }, function (message) {
          deferred.reject(message);
        });
      }, function (error) {
        $log.error('Failed to get the correct FILE_URI: ' + error);
        deferred.reject('Error while processing a picture.');
      });

      return deferred.promise;
    }

    function getCorrectFileUriAndBase64Data(uri) {
      var deferred = $q.defer();

      filenameWithExtension = uri.substr(uri.lastIndexOf('/') + 1);
      var extension = filenameWithExtension.substr(filenameWithExtension.lastIndexOf('.') + 1);

      if (!isFileSupported(extension)) {
        $log.error('Selected file\'s extension is not supported: ' + extension);
        deferred.reject('File type not supported');
      } else {
        window.plugins.Base64.encodeFile(uri, function (base64) {
          deferred.resolve({base64: base64, uri: uri});
        }, function (error) {
          $log.error('Failed to convert to base64: ' + error);
          deferred.reject('Error while processing a picture.');
        })
      }

      return deferred.promise;
    }

    function isFileSupported(extension) {
      switch (extension) {
        case 'bmp':<commit_msg>Prettify usage of promises.<commit_after>/*
 * Copyright 2016 <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

angular.module('symphonia.services')
  .factory('ImageLoadService', function ($q, $log, $cordovaCamera, $cordovaDevice) {
    var imageFileUri = '';
    var filenameWithExtension = '';
    var base64Data = '';
    var mime = 'image/*';

    function getPicture(sourceType) {
      var options = {
        destinationType: Camera.DestinationType.FILE_URI,
        mediaType: Camera.MediaType.PICTURE,
        sourceType: sourceType,
        saveToPhoroAlbum: sourceType === Camera.PictureSourceType.CAMERA
      };

      return $cordovaCamera.getPicture(options).then(function (newUri) {
        switch ($cordovaDevice.getPlatform()) {
          case 'iOS':
            return isIos(newUri);
          case 'Android':
            return isAndroid(newUri);
          default:
            return $q.reject('');
        }
      }, function (error) {
        if (error.toUpperCase() === 'Selection cancelled.'.toUpperCase() ||
          error.toUpperCase() === 'Camera cancelled.'.toUpperCase() ||
          error.toUpperCase() === 'no image selected'.toUpperCase()) {
          // When cancelled by user, we do not want to show error dialog.
          // FIXME: maybe there is some another error message when camera cancelled on iOS.
          // #wontfix until there is a opportunity to try on the real iOS device (not just simulator)
          return $q.resolve();
        }
        $log.error('Failed to pick a photo: ' + error);
        return $q.reject('Error while processing a picture.');
      });
    }

    function isIos(uri) {
      return getCorrectFileUriAndBase64Data(uri).then(function (uriAndRawBase64) {
        base64Data = uriAndRawBase64.base64;
        imageFileUri = uriAndRawBase64.uri;
        return $q.resolve();
      }, function (message) {
        return $q.reject(message);
      });
    }

    function isAndroid(uri) {
      return resolveNativePathPromiseWrapper(uri).then(function (correctUri) {
        return getCorrectFileUriAndBase64Data(correctUri).then(function (uriAndRawBase64) {
          base64Data = uriAndRawBase64.base64;
          imageFileUri = uriAndRawBase64.uri;
          return $q.resolve();
        }, function(message) {
          return $q.reject(message);
        })
      }, function (error) {
        $log.error('Failed to get the correct FILE_URI: ' + error);
        return $q.reject('Error while processing a picture.');
      });
    }

    function resolveNativePathPromiseWrapper(uri) {
      var deferred = $q.defer();

      window.FilePath.resolveNativePath(uri, function (correctUri) {
        deferred.resolve(correctUri);
      }, function (error) {
        deferred.reject(error);
      });

      return deferred.promise;
    }

    function getCorrectFileUriAndBase64Data(uri) {
      var deferred = $q.defer();

      filenameWithExtension = uri.substr(uri.lastIndexOf('/') + 1);
      var extension = filenameWithExtension.substr(filenameWithExtension.lastIndexOf('.') + 1);

      if (!isFileSupported(extension)) {
        $log.error('Selected file\'s extension is not supported: ' + extension);
        deferred.reject('File type not supported');
      } else {
        window.plugins.Base64.encodeFile(uri, function (base64) {
          deferred.resolve({base64: base64, uri: uri});
        }, function (error) {
          $log.error('Failed to convert to base64: ' + error);
          deferred.reject('Error while processing a picture.');
        })
      }

      return deferred.promise;
    }

    function isFileSupported(extension) {
      switch (extension) {
        case 'bmp':
{'fraction_non_alphanumeric': 0.11448908191579202, 'fraction_numerical': 0.01158161418747738, 'mean_word_length': 2.6697653829127934, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2472796', 'n_tokens_mistral': 2323, 'n_tokens_neox': 2233, 'n_words': 627}