import os
import misc

from quixote import get_publisher, get_request

from storage import StorableObject

class Host(StorableObject):
    _names = 'hosts'

    # Main settings
    label = None
    name = None
    orig_site = None
    auth_url = None
    auth_form_page_url = None
    auth_form = None
    logout_url = None
    reversed_hostname = None
    reversed_directory = None
    organization_name = None
    use_ssl = False
    private_key = None
    public_key = None

    # Auto detected settings
    auth_mode = 'form'
    auth_check_url = None
    login_field_name = None
    password_field_name = None

    # Advanced settings
    return_url = '/'
    root_url = None
    auth_system = 'password'
    auth_match_text = ''
    send_hidden_fields = True

    provider_id = None

    def get_host_from_url(cls):
        try:
            return list(Host.select(lambda x: x.name == misc.get_proxied_site_name()))[0]
        except:
            return None
    get_host_from_url = classmethod(get_host_from_url)

    def get_root_url(self):
        if self.root_url:
            return self.root_url
        if self.reversed_directory is not None:
            return '%s/%s/' % (get_request().environ['SCRIPT_NAME'], self.reversed_directory)
        else:
            return '%s/' % get_request().environ['SCRIPT_NAME']

    def get_return_url(self):
        if self.return_url.startswith('/'):
            if self.reversed_directory is not None:
                return '%s/%s%s' % (get_request().environ['SCRIPT_NAME'], self.reversed_directory, self.return_url)
            else:
                return '%s%s' % (get_request().environ['SCRIPT_NAME'], self.return_url)
        # In this case, must be a full url                
        return self.return_url

    def __cmp__(self, other):
        hostname_cmp = cmp(self.reversed_hostname, other.reversed_hostname)
        if hostname_cmp != 0:
            return hostname_cmp
        return cmp(self.reversed_directory, other.reversed_directory)
