#
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Intel, Inc.
#
#    This program 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; version 2 of the License.
#
#    This program 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, write to the Free Software
#    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
"""IRIS requests client"""


import sys
import urlparse
import traceback

import requests


class IrisRestClient(object):
    """IRIS Rest Client"""
    def __init__(self, server, user=None, pwd=None, verify=False):
        self.server = server
        self.session = None
        self.csrftoken = None
        self.header = None
        self.verify = verify
        if user:
            self._login(user, pwd)

    def _login(self, user, pwd):
        """
        Get csrftoken from server address, use csrftoken to login server,
        then get new csrftoken for accessing the server.
        """
        session = requests.Session()
        session.verify = self.verify
        try:
            session.get(urlparse.urljoin(self.server, '/login/'))
        except:
            traceback.print_exc()
            return False

        csrftoken = session.cookies.get('csrftoken')
        if not csrftoken:
            print >> sys.stderr, "Can't get csrf token"
            return False

        data = dict(username=user, password=pwd)
        header = {'X-CSRFToken': csrftoken}

        try:
            session.post(
                urlparse.urljoin(self.server, '/login/'),
                data=data,
                headers=header)
        except:
            traceback.print_exc()
            return False

        csrftoken = session.cookies.get('csrftoken')
        if not csrftoken:
            print >> sys.stderr, "Can't get csrf token2"
            return False

        self.header = {'X-CSRFToken': csrftoken}
        self.csrftoken = csrftoken
        self.session = session
        return True

    def _post(self, url, **kwargs):
        """Commom post method with header"""
        if not self.session:
            return {
                'status': 'Error',
                'detail': 'Client error! Please connect to the correct server',
                }
        try:
            res = self.session.post(
                urlparse.urljoin(self.server, url),
                headers=self.header,
                **kwargs)
            detail = res.json()
        except:
            traceback.print_exc()
            detail = {
                'status': 'Error',
                'detail': traceback.format_exc(),
                }
        else:
            detail['status'] = res.status_code

        return detail

    def scm_update(self, domain_file, gittree_file):
        """Update scm data to IRIS"""
        with open(domain_file, 'rb') as domains, \
             open(gittree_file, 'rb') as gittrees:
            files = (('domains', domains), ('gittrees', gittrees))
            return self._post('app/packagedb/scm/update/', files=files)

    def scm_check(self, domain_file, gittree_file):
        """Check scm project"""
        with open(domain_file, 'rb') as domains, \
             open(gittree_file, 'rb') as gittrees:
            files = (('domains', domains), ('gittrees', gittrees))
            return self._post('app/packagedb/scm/check/', files=files)

    def publish_event(self, typ, data):
        """
        Publish submissions related events to IRIS server
        """
        url = 'api/submissions/events/%s/' % typ
        res = self._post(url, data=data)
        print >> sys.stderr, 'events|%s|%s' % (url, res)
        return res
