
from PyQt4 import QtGui,QtCore

from PIL import ImageGrab, ImageFilter, Image
import cv2
import numpy as np
from PyQt4.QtGui import QApplication, QMainWindow, QPushButton,QLabel, QVBoxLayout, QWidget

from pytank.Core import Settings
import os
import copy
from PyQt4.QtGui import QPalette






def replace_all(text, dic):
        for i, j in dic.iteritems():
            text = text.replace(i, j)
        return text


def CleanButtons():
    output = []
    for item in open(Settings.ButtonsLocation).readlines():
        if item not in output:
            output.append(item)
    output = list(set(output))
    output.sort()
    file = open(Settings.ButtonsLocation, 'w')
    for i in output:
        file.write(i)
    file.close()
    line_prepender(Settings.ButtonsLocation,"from pytank.Applications import *")
    line_prepender(Settings.ButtonsLocation,"import pytank")






class ExtendedQWidget(QtGui.QDialog):
    def __init__( self,  parent = None, text = 'Null'):
        super( ExtendedQWidget, self ).__init__( parent )


class ButtonEditor(ExtendedQWidget):
    def __init__(self,text,thresh,widget, parent=None):
        super(ButtonEditor, self).__init__(parent)
        self.communicate = Communicate()
        self.Threshold = Settings.Button_Treshhold
        self.NameOFButton = text
        self.NameOFButton = self.NameOFButton.replace('.','')
        self.NameOFButton = self.NameOFButton.replace('/','_')
        self.NameOFButton = self.NameOFButton.replace('\\','_')
        self.ButtonImageLocation = Settings.ImageLocation + self.NameOFButton + ".png"
        print'The ButtonImageLocation is ->' + self.ButtonImageLocation
        string = "Buttons." + self.NameOFButton
        self.initPictureOfButton()
        self.ThreshValue = thresh
        print self.ThreshValue
        self.initColors()
        self.AlreadyActivated = False
        self.MainWidget = widget
        self.InitUI()
        self.show()

    def initColors(self):
        self.screen = QtGui.QDesktopWidget().availableGeometry()
        self.width = self.screen.width()
        self.height = self.screen.height()
        Palette = QPalette()
        Gradient = QtGui.QLinearGradient(500,self.height / 2, 0, 720)
        Gradient.setColorAt(0.0, QtGui.QColor(77,175,227))
        Gradient.setColorAt(0.4, QtGui.QColor(255,255,255))
        Gradient.setColorAt(0.7, QtGui.QColor(77,175,227))
        Palette.setBrush(QPalette.Window, QtGui.QBrush(Gradient))
        self.setPalette(Palette)


    def InitUI(self):
        self.setWindowOpacity(0.95)
        self.setWindowTitle("Editor")
        screen = QtGui.QDesktopWidget().screenGeometry()
        width = screen.width()
        height = screen.height()
        self.resize(width/2,height/2)
        self.setFocus()
        self.initResult()
        self.initAddButtons()
        self.initcv()
        self.initThresholdSlider()
        self.initLayout()

    def initThresholdSlider(self):
        self.ThresholdSlider = QtGui.QSlider(QtCore.Qt.Horizontal,self)
        self.ThresholdSlider.setRange(0,100)
        self.ThresholdSlider.setValue(self.ThreshValue)
        wholeNumThresh = str(self.ThreshValue)
        wholeNumThresh = wholeNumThresh.replace("0.",'')
        wholeNumThresh = wholeNumThresh.replace(".",'')
        wholeNumThresh = wholeNumThresh + '0'


        self.ThresholdSlider.setSliderPosition(int(wholeNumThresh))
        self.ThresholdSlider.setFixedHeight(55)

        self.ThresholdSlider.setSingleStep(1)
        self.ThresholdSlider.sliderReleased.connect(self.changeValue)





    def initAddButtons(self):
        font = QtGui.QFont()
        font.Helvetica
        font.setPointSize(40)
        self.ThresholdLabel = QLabel()
        self.ThresholdLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.ThresholdLabel.setFont(font)
        self.ThresholdLabel.setText(str(self.ThreshValue))
        self.ThresholdLabel.setText(str(.77))
        self.SaveButton = PushButton()
        self.SaveButton.setText('Save')
        self.SaveButton.setFixedWidth(100)
        self.SaveButton.clicked.connect(self.save)
        self.CloseButton = PushButton()
        self.CloseButton.setText('Close')
        self.CloseButton.setFixedWidth(100)
        self.CloseButton.clicked.connect(self.closed)

    def closed(self):
        self.close()


    def save(self):
        with open (Settings.ButtonsLocation, "r") as myfile:
            self.ButttonString = myfile.read()
            myfile.close()

        NameOfButton = self.NameOFButton#configurator_security
        list = NameOfButton.split('_')
        application = list[0]
        applicationTitle = application.title()
        button = list[1]

        string = NameOfButton + ' = ' + 'Classes.Button(' + "'" + NameOfButton + '.png' + "'" + ',' + applicationTitle + ',' + "Threshold = " + str(self.Threshold) + ')' + '\n'
       
        #print string
        #input_file = open(Settings.ButtonsLocation, "r")
        #output_file = open(ImageScripterPath + "\\Processing\\Temp2.txt",'w')
        #for i, line in enumerate(input_file):
                #if line.startswith(NameOfButton):
                    #output_file.write(string)
                #else:
                    #output_file.write(line)
        #input_file.close()
        #output_file.close()


        with open(Settings.ButtonsLocation,"r") as input:
            with open(ImageScripterPath + "\\Processing\\Buttons.py","wb") as output:
                for line in input:
                    if not line.startswith(NameOfButton + ' = '):
                        output.write(line)
                    if line.startswith(NameOfButton + ' = '):
                        output.write(string)
        f = open(ImageScripterPath + "\\Processing\\Buttons.py")
        f1 = open(Settings.ButtonsLocation, 'w')

        for line in f.readlines():
                f1.write(line)

        f1.close()
        f.close()
        self.close()







        #Configurator_security = pytank.Classes.Button('Configurator_security.png',Configurator)






    def changeValue(self):
        value = self.ThresholdSlider.value()
        scaledValue = float(value)/100     #type of "value" is int so you need to convert it to float in order to get float type for "scaledValue"
        self.Threshold = scaledValue
        self.initcv(self.Threshold)
        self.Result.setPixmap(QtGui.QPixmap(ImageScripterPath + "\\CapturePictures\\res.png"))
        self.ThresholdLabel.setText(str(scaledValue))

    def initResult(self):
        os.chdir(ImageScripterPath + "\\CapturePictures")
        self.img1 = ImageGrab.grab() #Grab Screen shot with PIL

        self.img1 = np.array(self.img1) #Conver Pil for OpenCV
        self.img1 = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY)
        self.img1 = cv2.pyrDown(self.img1)
        cv2.imwrite('res.png',self.img1)
        self.Result = QtGui.QLabel()
        self.Result.setGeometry(10, 10, 400, 100)
        self.Result.setPixmap(QtGui.QPixmap(ImageScripterPath + "\\CapturePictures\\res.png"))

    def AddButtonsClicked(self):
        pass

    def initcv(self,threshold = .97):
       # os.chdir(ImageScripterPath + "\\TextEditor\\CapturePictures')

        if self.AlreadyActivated == False:
            self.img1 = ImageGrab.grab() #Grab Screen shot with PIL
            self.img1 = np.array(self.img1) #Conver Pil for OpenCV
            self.img1 = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY)
            self.img1 = cv2.pyrDown(self.img1)
            self.img2 = copy.copy(self.img1)
            self.img3 = copy.copy(self.img1)

            string1 = Settings.ImageLocation
            string2 = self.NameOFButton.replace('Configurator\\','')
            string2 = string2 + ".png"


            string = string1 + string2
            print string

            try:
                self.template = cv2.imread(self.ButtonImageLocation,0)
                self.template = cv2.pyrDown(self.template)
            except:
                self.template = cv2.imread(string)
                self.template = cv2.pyrDown(self.template)
                print 'yes'
            w, h = self.template.shape[::-1]
            num = 0
            res = cv2.matchTemplate(self.img1,self.template,cv2.TM_CCOEFF_NORMED)
            loc = np.where( res >= threshold)
            for pt in zip(*loc[::-1]):
                        x,y = pt
                        a,b = self.template.shape
                        cv2.rectangle(self.img2, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
            cv2.imwrite('res.png',self.img2)
            self.AlreadyActivated = True

        if self.AlreadyActivated == True:
            self.img2 = copy.copy(self.img3)
            w, h = self.template.shape[::-1]
            res = cv2.matchTemplate(self.img1,self.template,cv2.TM_CCOEFF_NORMED)
            loc = np.where( res >= threshold)
            for pt in zip(*loc[::-1]):
                        x,y = pt
                        a,b = self.template.shape
                        cv2.rectangle(self.img2, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
            cv2.imwrite('res.png',self.img2)
            self.AlreadyActivated = True














    def initPictureOfButton(self):
        self.PictureOfButton = QLabel()
        self.NameOFButton = self.NameOFButton.replace('/','_')
        self.NameOFButton = self.NameOFButton.replace('\\','_')
        self.pixmap = QtGui.QPixmap(self.ButtonImageLocation)
        self.PictureOfButton.setPixmap(self.pixmap)
        self.PictureOfButton.setAlignment(QtCore.Qt.AlignCenter)




    def initLayout(self):
        self.grid = QtGui.QGridLayout()
        self.grid.addWidget(self.Result, 1, 0)
        self.grid.addWidget(self.PictureOfButton,2,0)
        self.grid.addWidget(self.ThresholdSlider, 3, 0)
        self.grid.addWidget(self.ThresholdLabel,4,0)
        self.grid.addWidget(self.SaveButton,5,0)
        self.grid.addWidget(self.CloseButton,6,0)
        self.setLayout(self.grid)







    def closeEvent(self, QCloseEvent):
        self.communicate.ButtonEditorClosed.emit()


class Communicate(QtCore.QObject):
    ButtonEditorClosed = QtCore.pyqtSignal()

class PushButton(QtGui.QPushButton):
    def __init__(self, text = '', parent = None):
        QtGui.QPushButton.__init__(self, text, parent)
        GlobalFont = QtGui.QFont()
        self.setStyleSheet("background-color:white")
        GlobalFont.Helvetica
        GlobalFont.setPointSize(10)
        self.setFont(GlobalFont)
