# Copyright (c) 2015–2016 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import requests


def load_list(filename):
    """Load the list of women from file."""
    with open(filename, "r", encoding="utf-8") as f:
        lines = f.readlines()
    return format_names([line.strip() for line in lines])


def format_names(women):
    """Format the names for searching."""
    formatted = []
    for name in women:
        split = name.split(",")
        formatted.append(" ".join([split[1].strip(), split[0].strip()]) if len(split) == 2 else split[0].strip())
    return formatted


def search(women):
    """Do the search on the list of women."""
    for woman in women:
        find_page(woman)


def find_page(search_term):
    """Attempt to find a matching Wikipedia article for the given woman."""
    api_params = {"action": "opensearch",
                  "search": search_term,
                  "limit": 1,
                  "namespace": 0,
                  "format": "json"}
    r = requests.get(api_url, params=api_params, headers=headers)
    if r:
        print(r.json())
    else:
        print(None)


def main():
    women = load_list("women.txt")
    search(women)

if __name__ == "__main__":
    headers = {'user-agent': "women-social-reformers-on-wikipedia: https://github.com/molly/women-social-reformers-"
                             "on-wikipedia"}
    api_url = "https://en.wikipedia.org/w/api.php"
    main()