#!/bin/python
"""
A script for generating A5 size pdf zines
with a text-file input, under development,
GPL3 Licence, Mara Karagianni May 2021
"""
import os
import random
import subprocess
import sys

from zine_maker import Zine


def shuffle_zine(finput, foutput):
    # set font for all text
    zine = Zine(orientation="P", unit="mm", format="A5")
    chapter_list = zine.shuffle_chapters(finput)

    with open('chapters.txt', 'w') as chapt:
        for i in chapter_list:
            chapt.write(i)
            chapt.write("\n")

    proc = subprocess.Popen(
        ["pdfunite"] + chapter_list + [foutput],
#        ["pdftk"] + ["$(cat chapters.txt)", "cat", "output"] + [foutput],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, err = proc.communicate()
    if err:
        print("Something went wrong!", err.decode('utf-8'), sep="\n")
    else:
        print("PDF saved as {}".format(foutput))
    os.system("mv ./*_chapter.pdf ./.tmp")
    os.system("rm ./.tmp/*_chapter.pdf")


if __name__ == '__main__':
    # file to get the text
    if len(sys.argv) > 1:
        if len(sys.argv) == 3:
            output = sys.argv[2]
        filename = sys.argv[1]
    else:
        filename = "./zines/zinemaker_screen.pdf"
        output = "./zines/zinemaker{}.pdf".format(random.randint(1, 40))

    shuffle_zine(filename, output)
