AtlasDs = Class.extend({
    init: function() {
        this.api = 'atlasds';
        this.apiUser = 'tester';
        this.apiKey = 'tester';
        this.apiUrl = '/api/';
        this.apiData = {'api':this.api,'apiUser':this.apiUser,'apiKey':this.apiKey};
    },

    addTestScrape: function() {
        var self = this;

        var addTestScrapeData = self.apiData;
        addTestScrapeData['url'] = $('#url').val();
        addTestScrapeData['regex'] = $('#regex').val();
        addTestScrapeData['dataType'] = $('#dataType').val();
        addTestScrapeData['command'] = 'addTestScrape';

        $('#scrapeForm').html('<p><img src="/images/ajax-loader.gif" alt="" /> Submitting scrape request to Atlas...</p>');

        $.post(self.apiUrl, addTestScrapeData, function(json) {
            $('#scrapeForm').html('<p><img src="/images/ajax-loader.gif" alt="" /> Scrape received by Atlas, waiting for task completion...</p>');
            setTimeout(function() { checkTestScrapeStatus(json.response.tasksAddedIdentifierArray[0], 0) }, 1000);
        }, 'json');

        function checkTestScrapeStatus(id, attempts) {
            attempts++;
            var checkTestScrapeData = self.apiData;
            checkTestScrapeData['command'] = 'getTask';
            checkTestScrapeData['taskId'] = id;

            $.post(self.apiUrl, checkTestScrapeData, function(json) {
                $('#scrapeForm').html('\n\
                    <ul>\n\
                    <li>Status: <b>'+json.response.status+'</b></li>\n\
                    <li>Time Added: <b>'+json.response.time_added+'</b></li>\n\
                    <li>Check Out Time: <b>'+json.response.check_out_time+'</b></li>\n\
                    <li>Check In Time: <b>'+json.response.check_in_time+'</b></li>\n\
                    <li>TTL: <b>'+json.response.ttl+'</b></li>\n\
                    <li>TTL History: <b>'+JSON.stringify(json.response.ttl_history)+'</b></li>\n\
                    <li>Results: <b>'+JSON.stringify(json.response.results)+'</b></li>\n\
                    <ul>\n\
                ');

                if(json.response.status == 'not_started' || json.response.status == 'started' || json.response.status == 'failed') {
                    $('#scrapeForm').html('<p style="margin-bottom: 1em;">Task not complete, checking status again in five seconds. ('+attempts+' attempts)</p>' + $('#scrapeForm').html());

                    setTimeout(function() { checkTestScrapeStatus(id, attempts) }, 5000);
                }
            }, 'json');
        }
    }
});

atlasDs = new AtlasDs();
