#!/usr/bin/env python
# -*- coding: UTF8 -*-

# This file is part of PySms.
#
# PySms - A text messenger for various swiss providers
# Copyright (C) 2007 Andreas Maechler <amaechler@gmx.ch>
#
# PySms 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; either version 3 of the License, or
# (at your option) any later version.
# 
# PySms 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, see <http://www.gnu.org/licenses/>.


import urllib2
import os

def assign_cookielib():

  # this is for allowing simple checking of the library in use
  cj = None
  ClientCookie = None
  cookielib = None

  # Let's see if cookielib is available
  try:
    import cookielib
  except ImportError:
    # If importing cookielib fails
    print "Importing cookielib (python 2.4 and above) failed..."
    print "Trying to import ClientCookie..."
    
    try:
      import ClientCookie
    except ImportError:
      # No cookie library available
      print "Importing ClientCookie failed... PySms can't run without it."
      exit
    else:
      # importing ClientCookie worked
      urlopen = ClientCookie.urlopen
      Request = ClientCookie.Request
      cj = ClientCookie.LWPCookieJar()
      
  else:
    # importing cookielib worked
    urlopen = urllib2.urlopen
    Request = urllib2.Request
    cj = cookielib.LWPCookieJar()
    # This is a subclass of FileCookieJar
    # that has useful load and save methods

  if cj is not None:
    # we successfully imported
    # one of the two cookie handling modules
    
    # Now we need to get our Cookie Jar
    # installed in the opener;
    # for fetching URLs
    if cookielib is not None:
      # if we use cookielib
      # then we get the HTTPCookieProcessor
      # and install the opener in urllib2
      opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
      urllib2.install_opener(opener)

    else:
      # if we use ClientCookie
      # then we get the HTTPCookieProcessor
      # and install the opener in ClientCookie
      opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
      ClientCookie.install_opener(opener)

  return (cj, urlopen, Request)
