import threading
from threading import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
import subprocess
import requests
from bs4 import BeautifulSoup
import time
from pyfzf.pyfzf import FzfPrompt
import sqlite3
import os

fzf = FzfPrompt()
options = Options()
sleep = threading.Event()


def get_html(url):

    r = requests.get(url)
    soup = BeautifulSoup(r.text, "lxml")
    item = soup.find("div", class_ = "tabs-b video-box").find("iframe").get("src")
    return item

def get_translations(driver):
    time.sleep(1)
    try:
        driver.find_element(By.XPATH,"/html/body/div[1]/div").click()
        items = driver.find_elements(By.CLASS_NAME, value="list")
        table = [i.text for i in items]
        table = [i for i in table[0].split("\n")]
        a = fzf.prompt(table, ' --cycle')
        driver.find_element(By.XPATH,f"/html/body/div[1]/div/ul/li[{table.index(a[0])+1}]").click()
        time.sleep(1)
    except:
        print("Could not get different translations")

def get_quality(driver):

    try:
        time.sleep(1)
        driver.find_element(By.XPATH, "/html/body/div[2]/pjsdiv/pjsdiv[20]/pjsdiv[1]/pjsdiv").click()
        driver.find_element(By.XPATH, "/html/body/div[2]/pjsdiv/pjsdiv[27]/pjsdiv[1]/pjsdiv/pjsdiv[9]").click()
    except:
        time.sleep(1)
        driver.find_element(By.XPATH, "/html/body/div/pjsdiv/pjsdiv[20]/pjsdiv[1]/pjsdiv").click()
        driver.find_element(By.XPATH, "/html/body/div/pjsdiv/pjsdiv[27]/pjsdiv[1]/pjsdiv/pjsdiv[9]").click()

def get_film_lord(driver):

    try:
        step1 = driver.find_element(By.XPATH, "/html/body/div[2]/pjsdiv/pjsdiv[1]/video")
    except:
        step1 = driver.find_element(By.XPATH, "/html/body/div/pjsdiv/pjsdiv[1]/video")

    step2 = str(step1.get_attribute("src"))

    return step2

def get_film_zona(driver):
    try:
        step1 = driver.find_element(by=By.XPATH, value='//*[@id="player_html5_api"]')
    except:
        print("err")

    step2 = str(step1.get_attribute("src"))

    return step2

def with_player(link):

    print("Link to the movie:", link)
    choice = fzf.prompt(["mpv", "vlc"], '--cycle')[0]
    print("Wait. Film is loading ... ")
    try:
        if choice == 'mpv' or choice == 'ьзм' :
            subprocess.run(['mpv', link])
        elif choice == 'vlc' or choice == 'мдс':
            subprocess.run(['vlc', link])
    except:
        print("Error")

def get_link():
    Database = sqlite3.connect("Film_list.db")
    cur = Database.cursor()
    a=cur.execute("SELECT COUNT (*) FROM Film_list").fetchall()[0][0]
    name_list = ['']*a
    i=0
    for name in cur.execute("SELECT NAME FROM Film_list "):
        name_list[i]=name[0]
        i+=1
    names = fzf.prompt(name_list, '--cycle')[0]

    with open("link.txt", 'w', encoding='utf8') as file:
        file.write(next(cur.execute(f"SELECT LINK FROM Film_list WHERE NAME='{names}'"))[0])
        sleep.set()

def clear_txt():
    try:
        path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'link.txt')
        os.remove(path)
    except:
        pass

def start_browser():
    print("Wait. Browser is loading ...")



    options.page_load_strategy="eager"
    #options.headless = True
    driver = webdriver.Firefox(options=options)
    
    sleep.wait()
    with open('link.txt',encoding='utf8') as file:
        url = file.read()

   
    try: 
        print("Translations are loading...")
        driver.get(url)

        if url.find("zona") != -1:
            driver.get(url)
            time.sleep(1)
            link = get_film_zona(driver)
        elif url.find("lord") != -1:
            url = get_html(url)
            driver.get(url)
            get_translations(driver)
            print("Wait quality is loading... ")
            get_quality(driver)
            link = get_film_lord(driver)

    except:
        print("Download film error")
        
    finally:
        clear_txt()
        driver.close()
        driver.quit()

    with_player(link)

if __name__=="__main__":

    t1=Thread(target=start_browser)
    t2=Thread(target=get_link)

    t1.start()
    t2.start()

    t2.join()
    t1.join()




