class IterationService:
    """
    Provides services to interact with Project iteration, handle operaions of list, create and retrieve iteration Resources
    """
    def __init__(self, base_url, usrname = None, apikey = None):
        self.restclient = RestClient(base_url)
        self.username = usrname
        self.apikey = apikey

    def get(self, projectid, iterationid):
        """
        Retrieve a specified Iteration Resource on Flies server
        @param projectid: Id of Project Resource
        @param iterationid: Id of Iteration Resource
        @return: Iteration object
        @raise NoSuchProjectException:
        """
        res, content = self.restclient.request_get('/seam/resource/restv1/projects/p/%s/iterations/i/%s'%(projectid,iterationid))
        
        if res['status'] == '200' or res['status'] == '304':
            server_return = json.loads(content)
            if server_return.has_key('status'):
                if server_return['status'] == "Retired":
                    print "Warning: The version %s is retired!"%iterationid
            return Iteration(server_return)
        elif res['status'] == '404':
            raise NoSuchProjectException('Error 404', content)
  
    def create(self, projectid, iteration):
        """
        Create a Iteration Resource on Flies Server
        @param projectid: Id of Project Resource
        @param iteration: Iteration object
        @return: Success if status of response is 201
        @raise ProjectExistException:
        @raise NoSuchProjectException:
        @raise UnAuthorizedException:
        @raise BadRequestException:
        """ 
        headers = {}
        headers['X-Auth-User'] = self.username
        headers['X-Auth-Token'] = self.apikey
         
        body = '''{"name":"%s","id":"%s","description":"%s"}'''%(iteration.name, iteration.id, iteration.desc)
        res, content = self.restclient.request_put('/seam/resource/restv1/projects/p/%s/iterations/i/%s'%(projectid,iteration.id), args=body, headers=headers)
         
        if res['status'] == '201':
            return "Success"
        elif res['status'] == '200':
            raise ProjectExistException('Status 200', "The version is already exist on server")
        elif res['status'] == '404':
            raise NoSuchProjectException('Error 404', content)
        elif res['status'] == '401':
            raise UnAuthorizedException('Error 401', 'This operation is not authorized, please check username and apikey')
        elif res['status'] == '405':
            raise NotAllowedException('Error 405', 'The requested method is not allowed')

    def delete(self):
        pass
class IterationService(Service):
    """
    Provides services to interact with Project iteration, handle operaions of list, create and retrieve iteration Resources
    """
    def __init__(self, base_url, usrname = None, apikey = None, http_headers = None):
        self.base_url = base_url
        self.restclient = RestClient(base_url)
        self.username = usrname
        self.apikey = apikey
        self.headers = http_headers  

    def disable_ssl_cert_validation(self):
        self.restclient.disable_ssl_cert_validation()

    def get(self, projectid, iterationid):
        """
        Retrieve a specified Iteration Resource on Zanata server
        @param projectid: Id of Project Resource
        @param iterationid: Id of Iteration Resource
        @return: Iteration object
        @raise NoSuchProjectException:
        """
        #res, content = self.restclient.request_get('/seam/resource/restv1/projects/p/%s/iterations/i/%s'%(projectid,iterationid))
        if self.headers:
            self.headers['Accept'] = 'application/json'
        res, content = self.restclient.request(self.base_url+'/seam/resource/restv1/projects/p/%s/iterations/i/%s'%(projectid,iterationid),"get",None,self.headers)
        server_return = self.messages(res,content)
        if server_return.has_key('status'):
            if server_return['status'] == "Retired":
                print "Warning: The project %s is retired!" %iterationid
        return Iteration(server_return)

    def create(self, projectid, iteration):
        """
        Create a Iteration Resource on Zanata Server
        @param projectid: Id of Project Resource
        @param iteration: Iteration object
        @return: Success if status of response is 201
        @raise ProjectExistException:
        @raise NoSuchProjectException:
        @raise UnAuthorizedException:
        @raise BadRequestException:
        """ 
        headers = {}
        headers['X-Auth-User'] = self.username
        headers['X-Auth-Token'] = self.apikey
         
        body = '''{"name":"%s","id":"%s","description":"%s"}'''%(iteration.name, iteration.id, iteration.desc)
        res, content = self.restclient.request_put('/seam/resource/restv1/projects/p/%s/iterations/i/%s'%(projectid,iteration.id), args=body, headers=headers)
        self.messages(res,content,"The Version is already exist on server")

    def delete(self):
        pass
class GlossaryService:
    def __init__(self, base_url):
        self.restclient = RestClient(base_url)

    def commit_glossary(self, username, apikey, resources):
        headers = {}
        headers['X-Auth-User'] = username
        headers['X-Auth-Token'] = apikey        
        
        res, content = self.restclient.request_put('/seam/resource/restv1/glossary', args=resources, headers=headers)
       
        if res['status'] == '201':
            return True
        elif res['status'] == '401':
            raise UnAuthorizedException('Error 401', 'This operation is not authorized, please check username and apikey')
        elif res['status'] == '400':
            raise BadRequestBodyException('Error 400', content)
        elif res['status'] == '503':
            raise UnavailableServiceError('Error 503', 'Service Temporarily Unavailable')
        else:
            raise UnexpectedStatusException('Error', 'Unexpected Status, failed to push')
class GlossaryService(Service):
    def __init__(self, base_url):
        self.restclient = RestClient(base_url)

    def commit_glossary(self, username, apikey, resources):
        headers = {}
        headers['X-Auth-User'] = username
        headers['X-Auth-Token'] = apikey
        res, content = self.restclient.request_put('/seam/resource/restv1/glossary',
                                                   args=resources, 
                                                   headers=headers)
        return self.messages(res,content)

    def delete(self, username, apikey, lang = None):
        headers = {}
        headers['X-Auth-User'] = username
        headers['X-Auth-Token'] = apikey
        resource = '/seam/resource/restv1/glossary'

        if lang:
            resource =  resource + '/'+lang

        res, content = self.restclient.request_delete(resource, headers=headers)
        return self.messages(res,content)
class ProjectService:
    """
    Provides services to interact with Project, handle operaions of list, create and retrieve Project Resources  
    """
    def __init__(self, base_url, usrname, apikey):
        self.restclient = RestClient(base_url)
        self.iterations = IterationService(base_url, usrname, apikey)
        self.username = usrname
        self.apikey = apikey

    def list(self):
        """
        List the Project Resources on the Flies server
        @return: list of Project object
        """
        res, content = self.restclient.request_get('/seam/resource/restv1/projects')
         
        if res['status'] == '200':
            projects = []
            projects_json = json.loads(content)
            
            for p in projects_json:
                projects.append(Project(p))
            return projects
       
    def get(self, projectid):
        """
        Retrieve a specified Project Resource on Flies server
        @param projectid: Id of Project Resource
        @return: Project object
        @raise NoSuchProjectException:
        """     
        res, content = self.restclient.request_get('/seam/resource/restv1/projects/p/%s'%projectid)
        if res['status'] == '200' or res['status'] == '304':
            project = Project(json.loads(content))
            project.set_iteration(self.iterations)
            return project
        elif res['status'] == '404':
            raise NoSuchProjectException('Error 404', content) 

    def create(self, project):
        """
        Create a Project Resource on Flies Server
        @param project: Project object
        @return: Success if status of response is 201
        @raise ProjectExistException:
        @raise NoSuchProjectException:
        @raise UnAuthorizedException:
        @raise BadRequestException:
        """
        headers = {}
        headers['X-Auth-User'] = self.username
        headers['X-Auth-Token'] = self.apikey
        body ='''{"name":"%s","id":"%s","description":"%s","type":"IterationProject"}'''%(project.name,project.id,project.desc)
        res, content = self.restclient.request_put('/seam/resource/restv1/projects/p/%s'%project.id, args=body, headers=headers)
        
        if res['status'] == '201':
            return "Success"
        elif res['status'] == '200':
            raise ProjectExistException('Status 200', "The project is already exist on server")
        elif res['status'] == '404':
            raise NoSuchProjectException('Error 404', content)
        elif res['status'] == '401':
            raise UnAuthorizedException('Error 401', 'This operation is not authorized, please check username and apikey')
        elif res['status'] == '400':
            raise BadRequestException('Error 400', content)
                    
    def delete(self):
        pass

    def status(self):
        pass
class ProjectService(Service):
    """
    Provides services to interact with Project, handle operaions of list, create and retrieve Project Resources  
    """
    def __init__(self, base_url, usrname, apikey,http_headers=None):
        self.http_headers = http_headers
        self.restclient = RestClient(base_url)
        self.iterations = IterationService(base_url, usrname, apikey,self.http_headers)
        self.username = usrname
        self.apikey = apikey
        self.base_url = base_url

    def disable_ssl_cert_validation(self):
        self.restclient.disable_ssl_cert_validation()
        self.iterations.disable_ssl_cert_validation()

    def list(self):
        """
        List the Project Resources on the Zanata server
        @return: list of Project object
        """
        res, content = self.restclient.request(self.base_url+'/seam/resource/restv1/projects',
                                               "get",
                                               None,
                                               self.http_headers)
        projects = []
        projects_json = self.messages(res,content)
        for p in projects_json:
            projects.append(Project(p))
        return projects

    def get(self, projectid):
        """
        Retrieve a specified Project Resource on Zanata server
        @param projectid: Id of Project Resource
        @return: Project object
        @raise NoSuchProjectException:
        """
        #res, content = self.restclient.request_get('/seam/resource/restv1/projects/p/%s'%projectid)
        
        if self.http_headers:
            self.http_headers['Accept'] = 'application/json'

        res, content = self.restclient.request(self.base_url+'/seam/resource/restv1/projects/p/%s'%projectid,"get",None,self.http_headers)
        server_return = self.messages(res,content)
        if server_return.has_key('status'):
            if server_return['status'] == "Retired":
                print "Warning: The project %s is retired!" % projectid

        project = Project(server_return)
        project.set_iteration(self.iterations)
        return project

    def create(self, project):
        """
        Create a Project Resource on Zanata Server
        @param project: Project object
        @return: Success if status of response is 201
        @raise ProjectExistException:
        @raise NoSuchProjectException:
        @raise UnAuthorizedException:
        @raise BadRequestException:
        """
        if self.http_headers:
            self.http_headers['Accept'] = 'application/json'
        body ='''{"name":"%s","id":"%s","description":"%s","type":"IterationProject"}'''%(project.name,project.id,project.desc)

        res, content = self.restclient.request_put('/seam/resource/restv1/projects/p/%s'%project.id, args=body, headers=self.http_headers)
        #res, content = self.restclient.request(self.base_url+'/seam/resource/restv1/projects/p/%s'%project.id,"put", body,self.http_headers)
        self.messages(res,content,"The project is already exist on server")

    def delete(self):
        pass

    def status(self):
        pass