/* Copyright fractalite */
(function () {
'use strict';
// Source: src/html/scripts/blocks-admin/edit.js
angular.module("blocks-admin", [])

// we have not declared direct dependency on $ocLazyLoad 
// but we know pine-admin does... is it bad ?
.controller('blocks_EditCtrl', function ($scope, $ocLazyLoad, $http, $q, $log) {

    var builders = {};

    /**
     * Loads dependecies for the block builder form
     * dependencies are declared in builder.admin.requires
     *
     * @param Object builder info
     *
     * @return
     * - promise of loading dependencies promise
     * - null if no dependencies
     */
    function loadDependencies(builder) {

        var promises = [];

        if (builder.admin.requires) {
            angular.forEach(
                builder.admin.requires,
                function (required) {
                    promises.push($ocLazyLoad.load(required));
                }
            )
        }

        promises = promises.concat(loadOptions(builder));

        return (promises.length === 0) ? null : $q.all(promises);
    }


    /**
     * looks for options this builder needs for its form
     * see pine-admin for more info on this "pattern"
     */
    function loadOptions(builder) {
        if (!builder.admin.options) return null;

        var opts = builder.admin.options,
            promises = [];

        var target = $scope.options[builder.type] = {};

        for (var key in opts) {
            if (opts[key].href) {
                promises.push(resolveOptions(target, key, opts[key].href));
            } else {
                target[key] = opts[key];
            }
        }
        return promises;
    }

    function resolveOptions(store, key, href) {
        return $http.get(href).then(function (res) {
            store[key] = res.data;
            return res.data;
        }, function () {
            return $q.reject('Could not load options ' + key + ' form ' + href);
        });
    }


    // When user changes block type,
    // - get the builder for that type
    // - put buidler in $scope after loading dependencies (if any)
    //
    // TODO this is async, ensure copy.type can't be changed while loading dependencies
    function blockTypeChanged(fresh, old) {

        if (fresh === undefined) {
            return;
        }

        if (!builders[fresh]) {
            throw new Error('Unknown builder ' + fresh);
        }

        if (fresh !== old || !$scope.builder) {

            var builder = builders[fresh];
            var promise = loadDependencies(builder);

            if ($scope.copy.isNew && builder.admin.defaults) {
              angular.extend($scope.copy, builder.admin.defaults);
            }

            if (promise === null) {
                $scope.builder = builder;
            } else {
                promise.then(function () {
                    $log.debug('block edit requires loaded');
                    $scope.builder = builder
                })
            }
        }

    }

    angular.forEach(
        $scope.options.builders,
        function (builder) {
            builders[builder.type] = builder;
        });




    $scope.$watch('copy.type', blockTypeChanged);





})

.controller('blocks_staticEditCtrl', function ($scope, $log) {

    var aceInstance;

    if (!$scope.copy.contentType) {
        $scope.copy.contentType = 'text';
    }

    // The ui-ace option
    $scope.aceOptions = {
        mode: $scope.copy.contentType,
        onLoad: function (_ace) {
            aceInstance = _ace;
            /*
       // HACK to have the ace instance in the scope...
       $scope.modeChanged = function () {
         _ace.getSession().setMode("ace/mode/" + $scope.mode.toLowerCase());
       };
       */

        }
    };

    $scope.contentTypeChanged = function () {
        aceInstance.getSession().setMode("ace/mode/" + $scope.copy.contentType);
    }

});
}());