import logging
from common.models import Job
from django.core.exceptions import ObjectDoesNotExist
from .models import CompareJobsManager


def get_job_objects(jobs):
    """
    returns list of users Job.objects
    :param jobs: list of jobs numbers
    """
    if not jobs:
        logging.warning('No jobs given to compare')
        return []
    try:
        job_objects = []
        for job in jobs:
            try:
                job = int(job)
                job_object = Job.objects.get(n=job)
                job_objects.append(job_object)
            except ObjectDoesNotExist:
                logging.error('No such job: {}'.format(job))
            except Exception:
                logging.error('Could not get job to compare', exc_info=True)
        return job_objects
    except Exception:
        logging.error('Could not get job objects for comparepage', exc_info=True)
        return []


def get_user_compare_job_objects(user):
    try:
        job_numbers = CompareJobsManager(user.login).get_jobs()
        job_objects = [Job.objects.get(n=job_n) for job_n in job_numbers]
        return job_objects
    except ObjectDoesNotExist:
        logging.warning("No {}'s compare_jobs".format(user.login))
        return []
    except:
        logging.exception("Could not get {}'s compare_jobs due to:".format(user.login))
        return []


def check_data_elements_equal(data):
    """
    checking if elements in data are all equal by iterating through them
    returns True or False
    returns True for empty lists
    :param data: list
    """
    try:
        iterator = iter(data)
        first = next(iterator)
        return all(first == rest for rest in iterator)
    except StopIteration:
        return True
    except:
        logging.exception('Could not check if elements in {} are equal due to:'.format(data))
        return False


def check_data_elements_empty(data):
    """
    checking if elements in data are all empty
    :param data: list
    """
    try:
        return not any(data)
    except:
        logging.exception('Could not check if elements in {} are empty due to:'.format(data))
        return False
