#!/usr/bin/env python
from sys import exit as sysexit
from json import decoder, load, dump
from os.path import isfile
from lib_pornhub import ph_config_dl_dir, ph_get_video
import ssl


try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context


filename = "video_list.json"
video_list = []
fl_video_list = []


def save_file():
    global filename, fl_video_list
    with open(filename, encoding="utf-8", mode="w") as f:
        dump(fl_video_list, f, indent=4)


def main():
    global filename, video_list, fl_video_list
    if not isfile(filename):
        print("File not found")
        sysexit()
    try:
        with open(filename, encoding="utf-8") as f:
            temp = load(f)
            video_list = temp.copy()
            fl_video_list = temp.copy()
    except decoder.JSONDecodeError:
        print("Syntax error, check file")
        sysexit()
    ph_config_dl_dir(None)
    video_len = len(video_list)
    count = 0
    for url in video_list:
        print('[+] URL: ' + url)
        ph_get_video(url)
        fl_video_list.remove(url)
        count += 1
        print("\nProcessed: {}/{}\n".format(count, video_len))
    save_file()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
    save_file()
