########################################################################
#
#  Copyright (C) 2009, CZ.NIC, z.s.p.o.
# 
#  This file is part of dnstester.
#
#  dnstester is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  dnstester is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################

import sys, time
import urllib
import urllib2
import hashlib
import socket

import config
import dnstests
import misc

def canonize(s):
    return s.replace('.', '_')

def upload(tests, other):
    
    if not config.id:
        return False

    data = {}

    for t in tests:
    	data[canonize('test_' + t.name + '_result')] = t.encoded_result()
    	data[canonize('test_' + t.name + '_log')] = t.msg

    for k, v in other.items():
    	data[canonize(k)] = v

    data.update(other)

    datakeys = data.keys()
    datakeys.sort()
    
    md5 = hashlib.md5()
    for k in datakeys:
        value = data[k].strip()
    	md5.update(value)
    md5.update(config.key)
    data['checksum'] = md5.hexdigest()

    # forced wait
    time.sleep(2)
    # optional longer wait
    if '--slowly' in sys.argv: time.sleep(10)

    request_data = urllib.urlencode(data)
    old_timeout =  socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(config.devdownload_timeout)
    	f = urllib2.urlopen(misc.get_upload_url(), request_data)
        status = f.code
    	s = f.read()
    	f.close()
        socket.setdefaulttimeout(old_timeout)
    except:
        socket.setdefaulttimeout(old_timeout)
    	return False

    return status == 200

def gathering(window):
    
        page_dev = window.pages[window.PAGE_SELECTDEVICE]
        list = {'tester_id': config.id, 'platform': sys.platform}
        list.update(page_dev.dev1.get_upload_list(''))
        if page_dev.dev2:
            list['config_simple'] = '0'
            list.update(page_dev.dev2.get_upload_list('2'))
        else:
            list['config_simple'] = '1'
            list.update(page_dev.dev1.get_empty_upload_list('2'))

        list.update(window.netinfo.get_data())

        return upload(dnstests.tests, list)

