(function(Trello, $) {

    var exportBrainstormer = function(idBrainstormer) {
        $.get('/api/v1.0/brainstormers/'+idBrainstormer)
        .done(function(brainstormer) {
            // Create Brainstormer with Board
            Trello.post('boards/', {'name': brainstormer.name}, function(board) {
                initBoard(board.id, function() {
                    //Create BrainstormerPropositionGroup with List
                    $.each(brainstormer.proposal_groups, function(key, value) {
                        Trello.post('lists/', {'name': value.name, 'idBoard': board.id}, function(list) {
                            // Create BrainstormerProposition with Card
                            $.each(value.propositions, function(key, value) {
                                Trello.post('lists/'+list.id+'/cards', {'name': value.text});
                            });
                        });
                    });
                });
            });
        });
    };

    var initBoard = function(idBoard, callback) {
        // Delete list provide at begining
        Trello.get('boards/'+idBoard+'/lists/', {}, function(lists) {
            $.each(lists, function(key, value) {
                Trello.put('lists/'+value.id+'/closed', {'value': 'true'});
            });
            callback();
        });
    };

    var updateLoggedIn = function() {
        var isLoggedIn = Trello.authorized();
        $(".connectTrello").toggle(!isLoggedIn);
        $(".exportTrello").toggleClass('disabled', !isLoggedIn);
    };

    $(function() {
        Trello.authorize({
            interactive: false,
            success: updateLoggedIn,
            error: updateLoggedIn
        });

        $("button.connectTrello")
        .click(function(){
            Trello.authorize({
                type: "popup",
                expiration: "1day",
                success: updateLoggedIn,
                error: updateLoggedIn,
                scope: { write: true, read: true }
            });
        });

        $(".exportTrello")
        .click(function() {
            var idBrainstormer = $(this).data('idbrainstormer');
            exportBrainstormer(idBrainstormer);
            $('.modal').modal('hide');
        });
    });

})(Trello, jQuery);
