import time, os
import requests

class SeafileClient:

    def __init__(self,server,username,password=None,token=None):
        self.server = server
        self.token = token
        self.login = (username,password)

    def api_endpoint(self):
        return "%s/api2/" % self.server

    def ping(self):
        try:
            return requests.get("%s/ping" % self.api_endpoint()).text == "pong"
        except:
            return False


    def obtain_token(self):
        user,passw = self.login
        try:
            req=requests.post("%s/auth-token/" % self.api_endpoint(), data = {'username': user, 'password': passw })
            json = req.json()
            if "non_field_errors" in json:
                print json["non_field_errors"]
                return False
            return SeafileToken(user,json["token"])
        except:
            return False

    def authorize(self):
        self.token = self.obtain_token()
        return self.token != False

    #curl -H 'Authorization: Token 24fd3c026886e3121b2ca630805ed425c272cb96' -H 'Accept: application/json; indent=4' https://cloud.seafile.com/api2/repos/
    def libraries(self):
        resp=requests.get("%s/repos/" % self.api_endpoint(), headers = {'Authorization': "Token %s" % self.token.token, 'Accept': 'application/json; indent=4' })
        if not resp.status_code == 200: return
        libraries=[]
        for lib in resp.json():
            if not lib['encrypted']:
                libraries.append(SeafileLibrary(self,lib['id'],lib['name'],lib['owner']))
        return libraries

class SeafileLibrary:

    def __init__(self,client,id,name,owner):
        self.client = client
        self.id = id
        self.name = name
        self.owner = owner

    def api_endpoint(self):
        return "%s/repos/%s" % (self.client.api_endpoint(),self.id)

    def upload(self,file,file_name,directory,link=None):
        def obtain_link():
            #curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" https://cloud.seafile.com/api2/repos/99b758e6-91ab-4265-b705-925367374cf0/upload-link/
            print "%s/upload-link" % self.api_endpoint()
            quoted = requests.get("%s/upload-link" % self.api_endpoint(), headers = {'Authorization': "Token %s" % self.client.token.token,}).text
            return quoted[1:-1]

        #curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=@test.txt -F filename=test.txt -F parent_dir=/ http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3
        resp = requests.post(link or obtain_link() ,
                      files={'file': (file_name,open(file, 'rb')), 'parent_dir': directory, 'target_file': "%s/%s" % (directory,file_name)},
                      headers = {'Authorization': "Token %s" % self.client.token.token,}
                      )
        if resp.status_code == 200:
            return SeafileFile(self,("%s/%s" % (directory,file_name)).replace('//','/').replace('//','/'),resp.text)
        return False

    #curl -H 'Authorization: Token f2210dacd3606d94ff8e61d99b477fd' -H 'Accept: application/json; charset=utf-8; indent=4' https://cloud.seafile.com/api2/repos/dae8cecc-2359-4d33-aa42-01b7846c4b32/file/detail/?p=/foo.c
    def file_info(self,path):
        resp=requests.get("%s/file/detail/?p=%s" % (self.api_endpoint(),path), headers = {'Authorization': "Token %s" % self.token.token, 'Accept': 'application/json; indent=4' })
        if resp.status_code == 200:
            json = resp.json()
            return SeafileFile(self,path,json['id'],json['size'])
        return False

    def __str__(self):
        return "%s on %s by %s" % (self.name,self.client.server,self.owner)

class SeafileFile:

    def __init__(self,library,path,id,size=0):
        self.id = id
        self.path = path
        self.library = library
        self.size = size

    #curl -v  -X PUT -d "p=/foo.md" -H 'Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd' -H 'Accept: application/json; indent=4' https://cloud.seafile.com/api2/repos/afc3b694-7d4c-4b8a-86a4-89c9f3261b12/file/shared-link/
    def share(self):
        resp = requests.put("%s/repos/%s/file/shared-link/" % (self.library.client.api_endpoint(),self.library.id),
                            headers = {'Authorization': "Token %s" % self.library.client.token.token, 'Accept': 'application/json; indent=4'},
                            data = {'p': self.path}
                            )
        return resp.headers.get("location")

    def update(self,file):
        def obtain_link():
            #curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" https://cloud.seafile.com/api2/repos/99b758e6-91ab-4265-b705-925367374cf0/upload-link/
            quoted = requests.get("%s/update-link" % self.library.api_endpoint(), headers = {'Authorization': "Token %s" % self.library.client.token.token,}).text
            return quoted[1:-1]
        directory, name = os.path.split(self.path)
        return self.library.upload(file,name,directory,obtain_link())

class SeafileToken:

    def __init__(self,username,token):
        self.username = username
        self.token = token

    def __str__(self):
        return "%s@%s" % (self.token,self.username)


