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

from PyQt5.QtCore import QThread
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog
from PyQt5 import QtGui
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot

import queue
import time
from Cafe import Cafe
import pickle

class Manager(QThread):
	def __init__(self,MainWindow, q, loop_time=1.0 / 60):
		self.MainWindow = MainWindow
		self.q = q
		self.timeout = loop_time

		self.Sleep_Time = 0

		self.Cafe_Class = Cafe.Naver()
		self.Running = False

		print ("Thread Creation Done")

		QThread.__init__(self)
	def __del__(self):
		self.wait()

	def onThread(self, function, *args, **kwargs):
		self.q.put((function, args, kwargs))


	def run(self):
		while True:
			try:
				function, args, kwargs = self.q.get(timeout=self.timeout)
				function(*args, **kwargs)
			except queue.Empty:
				self.idle()


	def idle(self):
		if(self.Running == True and self.Sleep_Time > 0):
			self.Sleep_Time -= 1
			time.sleep(1)
		else:
			if(self.Running == True):
				self.Sleep_Time = (int)(self.Delay)
				self.MainWindow.Progress_Text.setText("활성 리스트 파싱 시작")
				for index,row in enumerate(self.Activate_List):
					self.Activate_List[index][4] = self.Cafe_Class.Check(self, int(self.Activate_List[index][4]),row,self.MainWindow.Keyword_Input.toPlainText())
				self.MainWindow.Progress_Text.setText("알림 완료, 대기")

		pass
		# put the code you would have put in the `run` loop here

	def Login(self):
		self.MainWindow.Progress_Text.setText("로그인 진행중")
		self.Cafe_Class = Cafe.Naver(self.MainWindow.UserName_Input.toPlainText(), self.MainWindow.Password_Input.toPlainText())
		self.MainWindow.Progress_Text.setText("로그인 성공")

	def Get_Board(self):
		self.MainWindow.Progress_Text.setText("게시판 파싱 시작")
		self.Board_List = self.Cafe_Class.Get_Board()
		print("게시판 파싱 완료 피클링")
		with open ('Saved_Board.pkl', 'wb') as F:
			pickle.dump(self.Board_List, F)

		self.MainWindow.Progress_Text.setText("게시판 파싱 종료")

		for row in self.Board_List:
			rowPosition = self.MainWindow.Board_List.rowCount()
			self.MainWindow.Board_List.insertRow(rowPosition)
			#self.MainWindow.Progress_Text.setText("카페 : {} 게시판 : {} 등록".format(row[0],row[1]))
			self.MainWindow.Board_List.setItem(rowPosition, 0, QtWidgets.QTableWidgetItem("{}".format(row[0])))
			self.MainWindow.Board_List.setItem(rowPosition, 1, QtWidgets.QTableWidgetItem("{}".format(row[1])))
			self.MainWindow.Board_List.setItem(rowPosition, 2, QtWidgets.QTableWidgetItem("{}".format(row[2])))
			self.MainWindow.Board_List.setItem(rowPosition, 3, QtWidgets.QTableWidgetItem("{}".format(row[3])))

	def Start(self, Process_List):
		self.MainWindow.Progress_Text.setText("알림 프로그램 시작됨")
		self.Activate_List = list()

		self.Delay = int(float(self.MainWindow.Time_Box.currentText().replace('분','').strip()) * 60)

		for row in Process_List:
			if(row[1].count('전체 선택') == 0 and row[1].count('즐겨찾는 게시판') == 0 and row[3] == True):
				self.Activate_List.append(row)

		self.MainWindow.Progress_Text.setText("파싱할 게시판 설정 완료")

		Delete_List = list()
		Delete_Count = 0
		for index,row in enumerate(self.Activate_List):
			self.Activate_List[index][4] = self.Cafe_Class.Get_TopIndex(row)
			if (self.Activate_List[index][4] == -1):
				Delete_List.append(index)

		self.MainWindow.Progress_Text.setText("파싱 불가능 게시판 설정 완료")

		for d in Delete_List:
			Delete_Target = (int(d-Delete_Count))
			del(self.Activate_List[Delete_Target])


			Delete_Count += 1

		self.MainWindow.Progress_Text.setText("파싱 불가능 게시판 삭제 진행")

		print (self.Activate_List)

		self.Running = True


	def Notification(self,row):
		print (row)
		rowPosition = self.MainWindow.Log_List.rowCount()

		self.MainWindow.Log_List.insertRow(rowPosition)
		#카페 이름, 게시판 이름, 게시글 ID, 제목, url

		#self.MainWindow.Progress_Text.setText("카페 : {} 게시판 : {} 등록".format(row[0],row[1]))
		self.MainWindow.Log_List.setItem(rowPosition, 0, QtWidgets.QTableWidgetItem("{}".format(row[0])))
		self.MainWindow.Log_List.setItem(rowPosition, 1, QtWidgets.QTableWidgetItem("{}".format(row[1])))
		self.MainWindow.Log_List.setItem(rowPosition, 2, QtWidgets.QTableWidgetItem("{}".format(row[3])))
		self.MainWindow.Log_List.setItem(rowPosition, 3, QtWidgets.QTableWidgetItem("{}".format(row[4])))
		self.MainWindow.Log_List.setItem(rowPosition, 4, QtWidgets.QTableWidgetItem("{}".format(row[2])))
