#!/usr/bin/env python
'''
Copyright (C) 2013, Digium, Inc.
Jason Parker <jparker@digium.com>

This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''

import logging
import requests
import sys

from requests import codes
from twisted.internet import reactor

sys.path.append("lib/python")
from asterisk.asterisk import Asterisk
from asterisk.test_case import TestCase

LOGGER = logging.getLogger(__name__)

PORT=8088

def build_url(*args):
    return '/'.join([str(arg) for arg in args])

class Scenario(object):
    def __init__(self, userpass, method, expected_response):
        self.userpass = userpass
        self.method = method
        self.expected_response = expected_response

    def __repr__(self):
        return '{ userpass=%s, method=%s, expected=%d }' % (
            self.userpass, self.method.__name__, self.expected_response)

    def run(self, test, ast_instance, expect_headers):
        LOGGER.debug("Running %s" % self)
        # api_key auth
        resp = self.method("http://127.0.0.%d:%d/%s" % (ast_instance, PORT, build_url('ari', 'channels')),
                           params={'api_key': "%s:%s" % self.userpass},
                           headers={'Origin': "http://127.0.0.%d" % ast_instance})

        if self.expected_response != resp.status_code:
            LOGGER.error("Expected %d, got %d (%s). %s" % (
                self.expected_response, resp.status_code, resp.text, self))
            test.passed = False
            test.stop_reactor()

        if resp.headers.get('Access-Control-Allow-Origin') is None:
            if expect_headers == True:
                LOGGER.error("Expected Access-Control-Allow-Origin header.")
                test.passed = False
                test.stop_reactor()
        else:
            if expect_headers == False:
                LOGGER.error("Did not expect Access-Control-Allow-Origin header.")
                test.passed = False
                test.stop_reactor()


SCENARIOS=[
    Scenario(('cors', 'cors-pass'), requests.options, codes.no_content),
    Scenario(('cors', 'cors-pass'), requests.get,     codes.okay),
]

class ARICORSTest(TestCase):
    def __init__(self):
        TestCase.__init__(self)
        self.passed = True
        self.create_asterisk(4)

    def run(self):
        TestCase.run(self)
        self.run_scenarios(1, False)
        self.run_scenarios(2, True)
        self.run_scenarios(3, True)
        self.run_scenarios(4, False)

        self.stop_reactor()

    def run_scenarios(self, ast_instance, expect_headers):
        for scenario in SCENARIOS:
            if self.passed == False:
                return

            scenario.run(self, ast_instance, expect_headers)

def main():
    test = ARICORSTest()
    reactor.run()

    if test.passed:
        return 0
    return 1

if __name__ == "__main__":
    sys.exit(main() or 0)
