from PIL import Image, ImageDraw
import subprocess
import random
import os


if os.name == 'nt':
    FFMPEG_PROGRAM = 'ffmpeg.exe'
else:
    FFMPEG_PROGRAM = 'ffmpeg'


class Bars(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def _bars(self, spacing, background_color, bar_color):
        img = Image.new('RGB', (self.width, self.height), color=background_color)
        draw = ImageDraw.Draw(img)

        for x in range(0, self.width, spacing):
            draw.line( ((x,0), (x, self.width-1)), bar_color, 1)

        return img

    def make_black(self, dest_filename):
        counter = 0
        for spacing in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
            for frames in range(0,5):
                img = self._bars(spacing, 'black', 'white')
                filename = f'imgs/bars_black_{counter:05d}.png'
                img.save(filename)
                print(filename)
                counter += 1

        print('Calling ffmpeg to create black_bars.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/bars_black_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')

    def make_white(self, dest_filename):
        counter = 0
        for spacing in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
            for frames in range(0,5):
                img = self._bars(spacing, 'white', 'black')
                filename = f'imgs/bars_white_{counter:05d}.png'
                img.save(filename)
                print(filename)
                counter += 1

        print('Calling ffmpeg to create white_bars.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/bars_white_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')


class SolidBlack(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def make(self, dest_filename):
        img = Image.new('RGB', (self.width, self.height), color=(0, 0, 0))

        for frame in range(0, 25):
            filename = f'imgs/black_{frame:05d}.png'
            img.save(filename)
            print(f'Saving {filename}')

        print('Calling ffmpeg to create black_1s.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/black_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')


class Noise(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @staticmethod
    def noise_rect(width, height):
        img = Image.new('RGB', (width, height))
        draw = ImageDraw.Draw(img)

        # TODO img.load() for pixel access rather than the draw API :-)

        for x in range(0, width):
            for y in range(0, height):
                r = random.randint(0, 255)
                g = random.randint(0, 255)
                b = random.randint(0, 255)

                draw.point((x, y), (r, g, b))

        return img

    def make_fast(self, dest_filename):
        for frame in range(0,125):
            filename = f'imgs/noise_fast_{frame:05d}.png'
            # render noise at half size, and rescale using nearest neighbour (every pixel is now 2x2)
            img = self.noise_rect(int(self.width/2), int(self.height/2))
            img = img.resize((self.width, self.height), Image.Resampling.NEAREST)
            img.save(filename)
            print(f'Saved: {filename}')

        print('Calling ffmpeg to create noise_fast.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/noise_fast_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')

    def make_slow(self, dest_filename):
        counter = 0
        for frame in range(0,25):
            img = self.noise_rect(int(self.width/2), int(self.height/2))
            img = img.resize((self.width, self.height), Image.Resampling.NEAREST)

            for dupe in range(0, 5):
                filename = f'imgs/noise_slow_{counter:05d}.png'
                counter += 1
                img.save(filename)
                print(f'Saved: {filename}')


        print('Calling ffmpeg to create noise_slow.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/noise_slow_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')


class Gradient(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @staticmethod
    def gradient_rect(width, height):
        img = Image.new("RGB", (width, height))
        pixels = img.load()

        for y in range(height):
            for x in range(width):
                # Normalize x and y to [0, 1]
                nx = x / width
                ny = y / height

                # Calculate RGB values
                r = int(nx * 255)
                g = int(ny * 255)
                b = int((1 - (nx + ny) / 2) * 255)

                # Set pixel color
                pixels[x, y] = (r, g, b)

        return img

    def make(self, dest_filename):
        img = self.gradient_rect(self.width, self.height)

        for frame in range(0, 125):
            filename = f'imgs/gradient_{frame:05d}.png'
            img.save(filename)
            print(f'Saved: {filename}')

        print('Calling ffmpeg to create gradient.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/gradient_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')


class GradientWithNoise(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def make(self, dest_filename):
        bg = Gradient.gradient_rect(self.width, self.height)
        noise_height = int(self.height / 4)

        for frame in range(0, 125):
            noise = Noise.noise_rect(self.width, noise_height)
            x = 0
            y = (self.height / 2) - (noise_height / 2)
            bg.paste(noise, (x, int(y)))

            filename = f'imgs/gradient_noise_{frame:05d}.png'
            bg.save(filename)
            print(f'Saved: {filename}')

        print('Calling ffmpeg to create gradient_noise.mp4')
        subprocess.call([FFMPEG_PROGRAM, '-y', '-framerate', '25', '-i', 'imgs/gradient_noise_%05d.png', '-c:v', 'libx264rgb', '-crf',  '0', dest_filename])
        print('Done')
