#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

import time
import os

from nose.tools import *
from peewee import IntegrityError

from . import setup_each, teardown_each
from farnsworth.models import (ChallengeSet,
                               Exploit,
                               ExploitSubmissionCable,
                               RexJob,
                               Round,
                               Team)

class TestExploitSubmissionCable:
    def setup(self):
        setup_each()

    def teardown(self):
        teardown_each()

    def test_process_and_unprocessed(self):
        cs = ChallengeSet.create(name="foo")
        team = Team.create(name="opponent")
        exploit = Exploit.create(cs=cs, job=RexJob.create(), pov_type="type1",
                                 blob="abc", c_code="exploit it")
        Round.create(num=0)

        cable = ExploitSubmissionCable.create(team=team, cs=cs, exploit=exploit, throws=10, round=Round.current_round())

        assert_equals(len(ExploitSubmissionCable.unprocessed()), 1)

        cable.process()
        assert_equals(len(ExploitSubmissionCable.unprocessed()), 0)

    def test_most_recent(self):
        cs = ChallengeSet.create(name="foo")
        cs2 = ChallengeSet.create(name="bar")
        team = Team.create(name="opponent")
        exploit = Exploit.create(cs=cs, job=RexJob.create(), pov_type="type1",
                                 blob="abc", c_code="exploit it")
        exploit2 = Exploit.create(cs=cs2, job=RexJob.create(), pov_type="type1",
                                  blob="def", c_code="delfino")
        Round.create(num=0)

        cable = ExploitSubmissionCable.create(team=team, cs=cs, exploit=exploit, throws=10, round=Round.current_round())
        cable2 = ExploitSubmissionCable.create(team=team, cs=cs2, exploit=exploit2, throws=10, round=Round.current_round())
        assert_equals(len(ExploitSubmissionCable.most_recent()), 2)
        assert_items_equal(ExploitSubmissionCable.most_recent(), [cable, cable2])

        # assert we get back only the most recent exploit
        r1 = Round.create(num=1)
        new_exploit = Exploit.create(cs=cs, job=RexJob.create(), pov_type="type2",
                                     blob="def", c_code="don't exploit it")
        new_cable = ExploitSubmissionCable.create(team=team, cs=cs, exploit=new_exploit, throws=10, round=r1)
        assert_equals(len(ExploitSubmissionCable.most_recent()), 2)
        assert_items_equal(ExploitSubmissionCable.most_recent(), [new_cable, cable2])
