"""Negative controls for boot pixel and readiness evidence. Fixtures are not guest acceptance."""
import tempfile
import unittest
from pathlib import Path
from PIL import Image
from BootAnimationEvidence import BootAnimationCapture, inspect_boot_frame


class BootEvidenceGuards(unittest.TestCase):
    def test_black_is_allowed_but_unrelated_visible_pixels_are_not(self):
        image=Image.new('RGB',(1280,800))
        self.assertEqual(0,inspect_boot_frame(image)['OutsideNonBlackPixels'])
        for x,y in ((0,0),(640,4),(10,790),(1100,100)):
            with self.subTest(point=(x,y)):
                changed=image.copy();changed.putpixel((x,y),(0,255,255))
                with self.assertRaisesRegex(AssertionError,'outside'):inspect_boot_frame(changed)

    def test_old_top_progress_bar_is_rejected(self):
        image=Image.new('RGB',(1280,800));image.paste((56,199,164),(0,0,1280,10))
        with self.assertRaisesRegex(AssertionError,'outside'):inspect_boot_frame(image)

    def test_fast_readiness_cannot_skip_the_intro_or_release_after_an_app_frame(self):
        with tempfile.TemporaryDirectory() as directory:
            capture=BootAnimationCapture(Path(directory))
            capture.frames=[{'LogoPixels':200,'WordmarkPixels':30,'Sha256':str(i),'Phase':'Intro','LoaderPixels':0} for i in range(2)]
            markers='XFE_BOOT_VISUAL_START|\nXFE_BOOT_VISUAL_APPLICATION_FRAME_READY\nXFE_BOOT_VISUAL_INTRO_COMPLETE\n'
            valid=markers+'XFE_BOOT_VISUAL_RELEASED|ElapsedMs|2401|Frames|100|LoadingShown|0\nFIRST_FRAME'
            self.assertTrue(capture.finish(valid,'FIRST_FRAME')['Passed'])
            for invalid in (valid.replace('2401','2000'),valid.replace('XFE_BOOT_VISUAL_INTRO_COMPLETE','Missing'),
                            markers+'FIRST_FRAME\nXFE_BOOT_VISUAL_RELEASED|ElapsedMs|2401|Frames|100|LoadingShown|0'):
                with self.assertRaises(AssertionError):capture.finish(invalid,'FIRST_FRAME')

    def test_waiting_diagnostic_does_not_qualify_an_application_or_allow_early_release(self):
        with tempfile.TemporaryDirectory() as directory:
            capture=BootAnimationCapture(Path(directory))
            capture.frames=[{'LogoPixels':200,'WordmarkPixels':30,'Sha256':str(i),'Phase':'Waiting','LoaderPixels':10} for i in range(3)]
            serial='XFE_BOOT_VISUAL_START|\nXFE_BOOT_VISUAL_WAITING'
            result=capture.finish_waiting_diagnostic(serial)
            self.assertTrue(result['Passed']);self.assertFalse(result['ApplicationAcceptance'])
            for marker in ('XFE_BOOT_VISUAL_APPLICATION_FRAME_READY','XFE_BOOT_VISUAL_RELEASED|'):
                with self.assertRaises(AssertionError):capture.finish_waiting_diagnostic(serial+marker)


if __name__=='__main__':unittest.main()
