import _midgard as midgard

# Set up the repository config
configuration = midgard.config()
configuration.dbtype = 'SQLite'
configuration.database = 'midgardexample'
# this will store to SQLite in ~/.midgard2/data/midgardexample.db

# Open a Midgard repository connection
connection = midgard.connection()
connection.open_config(configuration)

import urllib, urllib2
import simplejson as json

class QaikuUser():
    user = None

    def __init__(self, username):
        try:
            self.user = midgard.db.user({'login': username, 'authtype': 'APIkey'})
        except:
            self.user = midgard.db.user()
            self.user.login = username
            self.user.authtype = 'APIkey'
            self.user.active = True
            self.user.create()
        
        if (self.user.password is None):
            self.ask_password()

        self.user.log_in()
    
    def ask_password(self):
        password = raw_input('Please type your Qaiku API key: ')
        
        if (self.check_password(password) is False):
            self.ask_password()
            
        self.user.password = password
        self.user.update()
            
    def check_password(self, password):
        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'adventure_tablet/0.1')]
        try:
            params = urllib.urlencode({'apikey': password})
            url = 'http://www.qaiku.com/api/statuses/user_timeline.json?%s' % params
            req = opener.open(url)
        except urllib2.HTTPError, e:
            print('Sorry, authorization failed.')
            return False
        except urllib2.URLError, e:
            print("Connection failed, error %s. Try again later" % (e.message))
            return False

        return True       
    
# Match OS user to Midgard user
import getpass
username = getpass.getuser()
  
user = QaikuUser(username)
print "Can has Qaiku"