# -*- coding: utf-8 -*-
from hdabo.models import Tag
from wikitools import api

def __is_homonymie(page_dict):
    for cat in page_dict.get(u"categories", []):
        if u'Catégorie:Homonymie' in cat.get(u"title", u"") or u'Category:Disambiguation pages' in cat.get(u"title", u""):
            return True
    return False

def query_wikipedia_title(site, label):
    
    params = {'action':'query', 'titles': label, 'prop':'info|categories', 'inprop':'url'}            
    wpquery = api.APIRequest(site, params) #@UndefinedVariable
    
    response = wpquery.query()    

    query_dict = response['query']
    # get page if multiple pages or none -> return Tag.null_result
    pages = query_dict.get("pages", {})
    if len(pages) > 1 or len(pages) == 0:
        return None, Tag.TAG_URL_STATUS_DICT["null_result"], None, None, response
    
    page = pages.values()[0]
    
    if u"invalid" in page or u"missing" in page:
        return None, Tag.TAG_URL_STATUS_DICT["null_result"], None, None, response

    url = page.get(u'fullurl', None)
    pageid = page.get(u'pageid', None)
    new_label = page[u'title']
    
    if __is_homonymie(page):
        status = Tag.TAG_URL_STATUS_DICT["homonyme"]
    elif u"redirect" in page:
        status = Tag.TAG_URL_STATUS_DICT["redirection"]
    else:
        status = Tag.TAG_URL_STATUS_DICT["match"]

    return new_label, status, url, pageid, response

