#!/usr/bin/env python
from sys import exit as sysexit
from os.path import isfile
from lib_pornhub import (
    ascii_banner, ph_config_dl_dir, ph_get_playlist, ph_get_video
)
from argparse import ArgumentParser
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


def main():
    parser = ArgumentParser()
    parser.add_argument('--url', type=str, help='URL of Pornhub video')
    parser.add_argument('--playlist', nargs='?', const='best', choices=['most-viewed', 'best', 'top-rated', 'longest'], help='Optional ordering of videos')
    parser.add_argument('--limit', type=int, help='Maximum number of videos', default=0)
    parser.add_argument('--dir', type=str, help='Output directory')
    parser.add_argument('--file', type=str, help='File with links to download')
    args = parser.parse_args()

    ################################
    ascii_banner("PornHub-dl")
    print("\t\tMade by tnt2402\n")
    print("\t\tModified by JDM17")
    print("\n\n\n########################################################\n")
    ################################

    ph_config_dl_dir(args.dir)
    if (args.url == None and args.playlist != None):
        print("URL cannot be empty!")
        sysexit()
    elif (args.playlist != None):
        ph_get_playlist(args.url, args.playlist, args.limit)
    elif (args.url != None):
        ph_get_video(args.url)
    elif (args.file != None):
        if not isfile(args.file):
            print("File not found")
            sysexit()
        with open(args.file, encoding="utf-8") as f:
            temp = list(filter(None, f.read().split("\n")))
            list_from_file = temp.copy()
            new_file = temp.copy()
        video_len = len(list_from_file)
        count = 0
        try:
            for url in list_from_file:
                print('[+] URL: ' + url)
                ph_get_video(url)
                new_file.remove(url)
                count += 1
                print("\nProcessed: {}/{}\n".format(count, video_len))
        except KeyboardInterrupt:
            pass
        with open(args.file, encoding="utf-8", mode="w") as f:
            for url in new_file:
                f.write(url + "\n")


if __name__ == '__main__':
    main()
