import json
import logging


def load_session(file_name, program):
    """
    Load and parse the Sublime session file provided, returning back a tuple
    containing the overall session file and the recent items. The tuple
    contains None if there are errors loading or parsing the session file.
    """
    try:
        with open(file_name, encoding="utf-8") as file:
            session = json.load(file)

            if program == "text":
                items = session["workspaces"]["recent_workspaces"]
                folders = session["folder_history"]
                files = [w["file_history"] for w in session["windows"] ]
                files.append(session["settings"]["new_window_settings"]["file_history"])
            else:
                items = session["recent"]
                folders = None
                files = None

            return (session, items, folders, files)

    except FileNotFoundError:
        logging.exception("Unable to locate session file")

    except ValueError:
        logging.exception("Session file could not be parsed; invalid JSON?")

    except KeyError:
        logging.exception("Session file could not be parsed; invalid format?")

    return (None, None, None, None)