# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'eror_window.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from pickle import NONE
import sys


from PyQt5.QtGui import *
from PyQt5.QtGui import *
from PyQt5.QtGui import *
from boto3 import resource
from pyqt5_plugins import *
import sqlite3
from sqlite3 import Error
from PyQt5 import QtCore, QtGui, QtWidgets
from PySide6.QtCore import *
from PySide6.QtUiTools import loadUiType
from PySide6.QtWidgets import *



#from main import UI_main_window
#import main
# from eror_window import *
# from main_window import *
# import main_window
# import detect_lenguage

import socket_client
from socket_client import tcpClient,Cloud
import arvanCloud
from setting_window import UI_setting_window
from arvanCloud import ProgressPercentage

class AlignDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(AlignDelegate, self).initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignCenter

class User:
    def __init__(self, username, password):
        self.password = password
        self.username = username
class Cloud:
    def _init_(self,access_key, secret_key, host, access_bucket):
        self.access_key = access_key
        self.secret_key = secret_key
        self.host = host
        self.access_bucket = access_bucket



ui, _ = loadUiType("main.ui")
class UI_main_window(QMainWindow, ui):
    secret_key=0
    access_key=0
    host=0
    access_buckets=[]
    sub_buckets=[]
    dst_path=''

    # tl_factory = pylon.TlFactory.GetInstance()
    # camera = pylon.InstantCamera()
    # camera.Attach(tl_factory.CreateFirstDevice())
    # camera.Open()
    # camera.StartGrabbing(1)
    # # grab = self.camera.RetrieveResult(2000, pylon.TimeoutHandling_Return)
    # converter = pylon.ImageFormatConverter()

    #grabResult = camera.RetrieveResult(4000, pylon.TimeoutHandling_ThrowException)
    def __init__(self):

        super(UI_main_window, self).__init__()
        self.setupUi(self)
        # Remove default frame
        flags = Qt.WindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.pos_ = self.pos()
        self.setWindowFlags(flags)
        self.show()
        self.activate_()
        self.downlaod_btn.clicked.connect(self.download)
        self.upload_btn.clicked.connect(self.upload)
        self.go_btn.clicked.connect(self.go)
        self.back_btn.clicked.connect(self.back)
        self.newfolder_btn.clicked.connect(self.new_folder)
        self.refresh_btn.clicked.connect(self.refresh)
        

        self.buttongroup = QButtonGroup()

    def establish_conn(self,obj,access_buckets,username):
        self.obj=obj
        self.access_buckets=access_buckets
        print(self.obj,access_buckets)
        self.create_buckets(self.access_buckets)
        self.arvan=arvanCloud.arvanCloud(self.obj)
        self.user_btn.setText(username)

    def refresh(self):
        self.create_buckets(self.access_buckets)
        self.arvan=arvanCloud.arvanCloud(self.obj)
        self.go()


    def create_buckets(self,bucketnames):
        table = self.tableWidget
        table.setColumnCount(len(bucketnames))
        table.setRowCount(1)
        table.setRowHeight(0,90)
        header = table.horizontalHeader() 
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        for button_number in range(len(bucketnames)):
            button = QPushButton(table)
            button.setText(str(bucketnames[button_number]))
            button.setObjectName(bucketnames[button_number])
            button.released.connect(self.click_bucket)
            button.setFont(QFont("Sanserif", 18))
            button.setIcon(QIcon("G:\work/abrarvan\images/folder-icon.png"))
            button.setIconSize(QSize(60,60))
            #self.horizontalLayout_5.addWidget(button)
            #print(self.secret_key)

            # create an cell widget
            table.setCellWidget( 0,button_number, button)

    def create_folders(self,folders):
        
        table = self.tableWidget_3
        table.setColumnCount(len(folders))
        table.setRowCount(1)
        table.setRowHeight(0,70)
        header = table.horizontalHeader() 
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        for button_number in range(len(folders)):
            button = QPushButton(table)
            button.setText(str(folders[button_number]))
            button.setObjectName(folders[button_number])
            button.released.connect(self.click_folder)
            button.setFont(QFont("Sanserif", 18))
            button.setIcon(QIcon("G:\work/abrarvan\images/folder-icon.png"))
            button.setIconSize(QSize(60,60))
            #self.horizontalLayout_5.addWidget(button)
            #print(self.secret_key)

            # create an cell widget
            table.setCellWidget( 0,button_number, button)


    def create_files(self,sub):
        
       # self.clearLayout(self.gridLayout)
        table = self.tableWidget_2
        table.setColumnCount(1)
        table.setRowCount(len(sub))
        #table.setTextAlignment(Qt.AlignVLeft) 
        #table.setRowHeight(0,90)
        header = table.horizontalHeader() 
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        for button_number in range(len(sub)):
            button = QPushButton()
            button.setText('  '+str(sub[button_number]))
            button.setObjectName(sub[button_number])
            #button.released.connect(self.click)
            button.released.connect(self.click_sub)
            button.setFont(QFont("Sanserif", 15))
            button.setIcon(QIcon("G:\work/abrarvan\images/file.png"))
            button.setIconSize(QSize(25,25))
            button.setStyleSheet("Text-align:left")
            table.setCellWidget( button_number,0, button)




    def split_file_folder(self,sub):
        folders=[]
        files=[]
        for i in range(len(sub)):
           # print(sub[i])
          #  print(sub[i].split('/',1))
          if len(sub[i].split('/',1))>1:
              folders.append(sub[i].split('/',1)[0])
          if len(sub[i].split('/',1))<=1:
              files.append(sub[i].split('/',1)[0])
                         
        my_finallist = [i for j, i in enumerate(folders) if i not in folders[:j]] 
        folders=list(my_finallist)
        print('folders',folders)
        print('files',files) 
        self.create_folders(folders)
        content=folders+files
        self.create_files(files)



    def clearLayout(self,layout):
        while layout.count():
            child = layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()


    # def on_button_clicked(self, id):
    #     for button in self.buttongroup.buttons():
    #         if button is self.buttongroup.button(id):
    #             self.label.setText(button.text() + " Was Clicked ")


    def click_bucket(self):
        btn = self.sender()
        btnName = btn.objectName()
      #  print(btnName)
        content=0
        bucket=self.arvan.get_bucket(btnName)
        print(bucket)
        self.bucket=bucket
        content=self.arvan.get_all_content(bucket)
     #   print(content)
        content_names=self.arvan.get_content_names(content)
      #  print(content_names)
       # self.create_subfolder(content_names)
        self.split_file_folder(content_names)
        self.dst_path=btnName
        self.path_line.setText(str(btnName)+'/')


    def click_sub(self):
        btn = self.sender()
        btnName = btn.objectName()
        print(btnName)
        self.dst_path=btnName
        self.path_line.setText(self.path_line.text()+btnName)
        print(self.dst_path)

    def click_folder(self):
        btn = self.sender()
        btnName = btn.objectName()
        print(btnName)
        self.dst_path=btnName
        print(self.dst_path)
        path=self.path_line.text()+btnName
        pathline=path
        print(path)
        bucket=path.split('/',1)[0]
        print(bucket)
        bucket=self.arvan.get_bucket(bucket)
        path=path.split('/',1)[1]
        path=path+'/'
        print(path)
        self.path_line.setText(pathline+'/')
        content=self.arvan.get_directory_content(bucket,path)
        print(content)
        print(content)
        self.split_file_folder(content)


      #  self.split_file_folder(content_names)

    def go(self):
        
        path=self.path_line.text()
        pathline=path
        print(path)
        bucket=path.split('/',1)[0]
        print(bucket)
        bucket=self.arvan.get_bucket(bucket)
        path=path.split('/',1)[1]
      #  path=path+'/'
        print(path)
      #  self.path_line.setText(pathline+'/')
        content=self.arvan.get_directory_content(bucket,path)
        print(content)
        self.split_file_folder(content)

    def back(self):
        path=self.path_line.text()
        pathline=path
        print(path)
        head_tail = os.path.split(path)
        path=head_tail[0]
        head_tail = os.path.split(path)
        path=head_tail[0]
        # print head and tail
        # of the specified path
        #print("Head of '% s:'" % path, head_tail[0])
        path=path+'/'
        self.path_line.setText(path)
        self.go()
#download------------

    def download(self):
        matching=[]
        self.getfiles()
        # self.src_path='G:\work/abrarvan/New folder'
        print(self.path_line.text().split('/',1)[1])
        path=self.path_line.text()
        print('path',path)
        path=path.split('/',1)[1]
        print('path',path)
        print('path',path)
        bucket=self.arvan.get_bucket(self.path_line.text().split('/',1)[0])
        print('bucket',bucket)
        
        contents = self.arvan.get_all_content(bucket)
        content_names = self.arvan.get_content_names(contents)
        print(content_names)
        
        contents=self.arvan.get_hirechy_content(path,content_names)
        print('contents',contents)
        if path !='':
            for i in range(len(contents)):
                contents[i]=path+contents[i]
            print('contents+path',contents)
            # self.arvan.download(self.bucket,self.src_path,content_names[3])
            # for i in range (len(x)):
            #     self.arvan.download(self.bucket,self.src_path,x[i])
                # if content_names[i].split('/',cont)[cont]==path:
                #     print('hi')
            # for i in range(len(contents)):    
            #         matching.append([s for s in content_names if contents[i] in s])
            # print(matching)
            if len(contents)>1:
                for i in range(1,len(contents)):
                    self.arvan.download(bucket,self.src_path,contents[i])
            else:
                for i in range(len(contents)):
                    self.arvan.download(bucket,self.src_path,contents[i])                
    def getfiles(self):
        self.src_path=str(QFileDialog.getExistingDirectory(None, "Select Directory"))
        print(self.src_path)
      #  self.src_path=os.path.join(self.src_path,'/')
      #  print(self.src_path)
        self.src_path=os.path.abspath(self.src_path)
        self.src_path=self.src_path+'/'
        print(self.src_path)

#upload---------
    def upload(self):
        upload_path=self.upload_path()
        print(upload_path)
      #  print(self.dst_path)
        path=self.path_line.text()
        print(path)
        bucket=path.split('/',1)[0]
        print(bucket)
        bucket=self.arvan.get_bucket(bucket)
        self.perc=ProgressPercentage(upload_path,self.progressBar)
        head_tail = os.path.split(upload_path)
        head_tail=head_tail[1]
        print('head_tail',head_tail)
        self.dst_path=path.split('/',1)[1]
        print(self.dst_path)
        self.dst_path=os.path.join(self.dst_path,head_tail)
        print(self.dst_path)
       # self.dst_path=self.dst_path+head_tail
        print('PATH',self.dst_path)
        self.arvan.upload(bucket,upload_path,self.dst_path,self.perc)
        
    def upload_path(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        if fileName:
            print(fileName) 

        return fileName

#new_folder-----------

    def new_folder(self):
        upload_path='data.xlsx'
        path=self.path_line.text()
        print(path)
        bucket=path.split('/',1)[0]
        print(bucket)
        bucket=self.arvan.get_bucket(bucket)

        self.dst_path=path.split('/',1)[1]
        print(self.dst_path)
        print(self.dst_path)
        self.dst_path=self.dst_path+self.newfolder_name.text()+'/'
       # self.dst_path=self.dst_path+head_tail
        print('PATH',self.dst_path)
        self.arvan.upload_2(bucket,upload_path,self.dst_path)
        self.newfolder_name.setText('')



#activate------------
    def activate_(self):
        self.close_btn.clicked.connect(self.close_win)
        self.maxiButton.clicked.connect(self.maxmize_minimize)
        self.miniButton.clicked.connect(self.minimize)


    def minimize(self):
        self.showMinimized()

    def close_win(self):
        self.close()
        sys.exit(app.exec())

    def maxmize_minimize(self):
        if self.isMaximized():
            self.showNormal()
        else:
            self.showMaximized()



#UI_login-----------
ui2, _ = loadUiType("login.ui")
class UI_login_window(QMainWindow, ui2):
    file_path=0,0,0,0,0
    global widgets
    widgets_eror = ui2
    image_glob=0
    clsoe_sign=0
    username=''
    ip='192.168.0.13'
    port=5000
    def __init__(self):
        super(UI_login_window, self).__init__()
        self.setupUi(self)
        # Remove default frame
        flags = Qt.WindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.pos_ = self.pos()
        self.setWindowFlags(flags)
        self.activate_()
        self.id=0
        self.lineEdit_password.setEchoMode(QLineEdit.Password)
        self.setting_win=UI_setting_window()
        self.setting_win.save_btn.clicked.connect(self.set_ipaddress)


    def activate_(self):
        self.close_btn.clicked.connect(self.close_win)
        self.login_btn.clicked.connect(self.send_login_info)
        self.setting_btn.clicked.connect(self.setting)
        

    def setting(self):
        self.setting_win.lineEdit.setText(str(self.ip))
        self.setting_win.lineEdit_2.setText(str(self.port))
        self.setting_win.show()


    def set_ipaddress(self):
        self.ip=self.setting_win.ip
        self.port=self.setting_win.port
        print(self.ip,self.port)
        

    def close_win(self):
        self.close()

    # def set_language(self):
    #     if detect_lenguage.language()=='Persian(فارسی)':
    #         detect_lenguage.login_window(self)

    def login_tempor(self):
        # app = QApplication()
        access_key='2159c713-f554-49d4-b0b5-c5025665fe18'
        access_buckets=['gits', 'malekzadeh', 'testpython']
        secret_key='0e816c03cf097c12b9a0327db853d41b7f194e21bc3681de265e76ba607c66e3'
        host='https://s3.ir-thr-at1.arvanstorage.com'
        self.username=self.lineEdit.text()
        obj=arvanCloud.Client(access_key, secret_key, host,access_buckets)
        self.window_22 = UI_main_window()
        self.window_22.establish_conn(obj,access_buckets,self.username)
        
        self.window_22.show()
        self.close()


        

    def send_login_info(self):
        username=self.lineEdit.text()
        password=self.lineEdit_password.text()
        user=User(username,password)
        print(user)
        obj=tcpClient(self.ip, 5000)
        
        ret=obj.login(user)
        print('ret',ret)
        if ret==False:
            print('server is down')
            self.label_2.setText(' server is down')
        elif ret.access_key:
            print(ret.access_key)
            print(ret.access_buckets)
            print(ret.secret_key)
            print(ret.host)
            self.window_22 = UI_main_window()
            self.window_22.establish_conn(obj,ret.access_buckets,self.username)
            
            self.window_22.show()


            
        elif ret.access_key==None:
            self.label_2.setText(' Invalid Username or password')
        elif ret.access_key:
            print(ret.access_key)
            print(ret.access_buckets)
            print(ret.secret_key)
            print(ret.host)

        # self.window.show()
        # self.close()

    def login_database(self):
        print('asdqwe')
        conn=self.create_connection('settings.db')
        cur = conn.cursor()
        # cur.execute('select * from login')
        #records = cur.fetchall()
        #print(records)
        try:
            query = 'SELECT password FROM login WHERE ID =\''+self.lineEdit.text()+"\'"
            cur.execute(query)
            self.label_2.setText("invalid Username or Password")
        except Error as e:
            print('eror')
            
        result_pass = cur.fetchone()[0]
        if result_pass == self.lineEdit_2.text():
            
            print("Successfully logged in.")
            self.label_2.setText("loged in")
            id=self.lineEdit.text()
            self.close()
            return id
        else:
            ret="Invalid Username or Password"
            self.label_2.setText(ret)
            return ret

    # def eror_window(self,msg,level):
    #     self.window = UI_eror_window()
    #    # self.ui2= UI_eror_window()
    #     self.window.show()
    #     self.window.set_text(msg,level)
    #     #self.close_sign=self.window.close_sign


             
    def create_connection(self,db_file):
        """ create a database connection to the SQLite database
            specified by db_file
        :param db_file: database file
        :return: Connection object or None
        """
        conn = None
        try:
            conn = sqlite3.connect(db_file)
            return conn
        except Error as e:
            print(e)
            self.eror_window(msg=' NO connection to database {}'.format(db_file),level=3)
 

if __name__ == "__main__":
    app = QApplication()
    win = UI_login_window()
    win.show()
    sys.exit(app.exec())

#2159c713-f554-49d4-b0b5-c5025665fe18
# 2159c713-f554-49d4-b0b5-c5025665fe18
# (1, 'amir', '1234', ['malekzadeh'])
# 0e816c03cf097c12b9a0327db853d41b7f194e21bc3681de265e76ba607c66e3
# https://s3.ir-thr-at1.arvanstorage.com



