import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QLineEdit, QVBoxLayout, QFileDialog, QWidget
import firebase_admin
from firebase_admin import credentials, storage

class VideoUploader(QMainWindow):
    def __init__(self):
        super(VideoUploader, self).__init__()

        # Initialize Firebase Admin SDK
        cred = credentials.Certificate("/home/knight/Python_Prog/UI/chatbot.json")
        firebase_admin.initialize_app(cred, {'storageBucket': 'chatbot-402717.appspot.com'})

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Video Uploader')
        self.setGeometry(100, 100, 400, 200)

        self.title_label = QLabel('Video Title:', self)
        self.title_input = QLineEdit(self)
        self.browse_button = QPushButton('Browse', self)
        self.upload_button = QPushButton('Upload', self)
        self.status_label = QLabel(self)

        layout = QVBoxLayout()
        layout.addWidget(self.title_label)
        layout.addWidget(self.title_input)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.upload_button)
        layout.addWidget(self.status_label)

        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.browse_button.clicked.connect(self.browse_video)
        self.upload_button.clicked.connect(self.upload_video)

    def browse_video(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getOpenFileName(self, "Choose Video File", "", "Video Files (*.mp4 *.mkv *.avi);;All Files (*)", options=options)
        if file_name:
            self.video_path = file_name
            self.status_label.setText(f'Selected video: {file_name}')

    def upload_video(self):
        try:
            title = self.title_input.text()
            if not title:
                self.status_label.setText('Please enter a title for the video.')
                return

            if not hasattr(self, 'video_path'):
                self.status_label.setText('Please select a video to upload.')
                return

            # Get a reference to the Firebase Storage bucket
            bucket = storage.bucket()

            # Upload the video to Firebase Storage within the specified title folder
            blob = bucket.blob(f'{title}/{title}.mp4')
            blob.upload_from_filename(self.video_path)
            print("Video path: ", self.video_path)

            self.status_label.setText('Video uploaded successfully.')

        except Exception as e:
            self.status_label.setText(f'Error: {str(e)}')
            print (e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = VideoUploader()
    window.show()
    sys.exit(app.exec_())