var PhotoView = (function () {
  'use strict';

  var csInterface = new CSInterface();

  return {
    insert: insertPhotos
  };

  function insertPhotos(photos, next_page_url, isFirstPage) {
    if (isFirstPage) {
      $('.js-photos').html('');
      if (photos.length) {
        $('.js-no-results').addClass('hidden');
      } else {
        $('.js-no-results').removeClass('hidden');
        PopularSearches.show();
      }
    }
    renderPhotos(photos);
    updateRowGridLayout(isFirstPage);
    addPhotoEventListener();
    if (next_page_url) {
      initEndlessScrolling(next_page_url);
    }
  }

  function renderPhotos(photos) {
    photos.forEach(function(photo) {
      var tpl = $('.js-photo-template');

      var imageTag = tpl.find('.js-photo');
      imageTag.attr('src', photo.src.medium);
      imageTag.attr('width', Math.ceil(350 / photo.height * photo.width));
      imageTag.attr('height', 350);
      imageTag.attr('data-original', photo.src.original);
      imageTag.attr('data-large', photo.src.large);
      imageTag.attr('data-id', photo.id);
      imageTag.attr('data-url', photo.url);

      var photoContainer = tpl.find('.photo-container');
      photoContainer.attr('data-size', photo.width + 'px x ' + photo.height + 'px');

      var insertPhotoButton = tpl.find('.js-insert-photo');

      var viewPhotoButton = tpl.find('.js-view-photo');
      viewPhotoButton.attr('onclick', 'Util.openUrl("' + photo.url + '")');

      var likeButton = tpl.find('.js-like-photo');
      likeButton.attr('data-photo-id', photo.id);
      likeButton.toggleClass('btn-like--active btn-like--no-animations', !!photo.liked);

      $('.js-photos').append(tpl.html());
    });
  }

  function updateRowGridLayout(isFirstPage) {
    var container = document.getElementsByClassName('js-photos')[0];
    if (isFirstPage) {
      rowGrid(container, {itemSelector: '.photo-container', minMargin: 5, maxMargin: 5, resize: true, minWidth: 500});
    } else {
      rowGrid(container, 'appended');
    }
  }

  function addPhotoEventListener() {
    var $newPhotos = $('.js-photos .js-new-photo');

    $newPhotos.on('mouseenter', function() {
      if (Settings.getDownloadSize() === 'original') {
        $('.js-size').text($(this).attr('data-size'));
      }
    });

    $newPhotos.find('.js-photo').on('click', function () {
      downloadAndOpen(
        $(this).attr('data-id'),
        $(this).attr('data-' + Settings.getDownloadSize()),
        $(this).attr('data-url')
      );
    });

    var likeButtons = $newPhotos.find('.js-like-photo');
    likeButtons.on('click', onLike);

    $newPhotos.removeClass('js-new-photo');
  }

  function onLike(event) {
    var likeButton = $(this);
    var photoId = likeButton.attr('data-photo-id');
    var isLiked = likeButton.hasClass('btn-like--active');
    likeButton.removeClass('btn-like--no-animations');
    likeButton.toggleClass('btn-like--active');
    Likes.toggleLike(photoId, isLiked);
  }

  function initEndlessScrolling(next_page_url) {
    $(document).off('scroll', onScroll);

    var data = { next_page_url: next_page_url };
    onScroll({data: data});

    $(document).on(
      'scroll',
      data,
      onScroll
    );
  }

  function onScroll(event) {
    if ((window.innerHeight + window.scrollY) >= ($(document).height() - 300)) {
      $(document).off('scroll', onScroll);
      PhotoApi.get(event.data.next_page_url);
    }
  }

  function downloadAndOpen(photo_id, downloadUrl, photoUrl) {
    Util.trackDownload(photo_id);
    var body = $('body');
    body.addClass('is-downloading');
    var name = 'pexels-photo';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', downloadUrl, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function (e) {
      if (this.status === 200 || this.status === 304) {
        var uInt8Array = new Uint8Array(this.response);
        var i = uInt8Array.length;
        var binaryString = new Array(i);
        while (i--)
          binaryString[i] = String.fromCharCode(uInt8Array[i]);
        var data = binaryString.join('');
        var base64 = window.btoa(data);

        var downloadedFile = createTempFolder() + name + '.jpg';

        window.cep.fs.writeFile(downloadedFile, base64, cep.encoding.Base64);
        var shouldClip = Settings.shouldClip();
        var photoTitle = getPhotoTitle(photoUrl);
        csInterface.evalScript(
          'insertImage("' + downloadedFile + '", ' + shouldClip + ', "' + photoTitle + '")'
        );
      }
      body.removeClass('is-downloading');
    };
    xhr.send();
  }

  function createTempFolder() {
    var tempFolderName = 'com.adobe.pexels.extension/';
    var tempFolder = '/tmp/' + tempFolderName;
    if (window.navigator.platform.toLowerCase().indexOf('win') > -1) {
      tempFolder = csInterface.getSystemPath(SystemPath.USER_DATA) + '/../Local/Temp/' + tempFolderName;
    }
    window.cep.fs.makedir(tempFolder);
    return tempFolder;
  }

  function getPhotoTitle(photoUrl) {
    photoUrl = photoUrl.replace(/\/$/, ''); // remove slash at the end
    photoUrl = photoUrl.split('/');
    return photoUrl[photoUrl.length - 1];
  }

}());