#encoding = utf8
import time
import logging

import win32com.client
import win32api
import win32con
import pythoncom

logger = logging.getLogger(__name__)

VK_CODE = {
    'spacebar': 0x20,
    'down_arrow': 0x28,
}


class PPTController:
    def __init__(self):
        pythoncom.CoInitialize()
        self.app = win32com.client.Dispatch("PowerPoint.Application")
        self.app.Visible = True

    def __del__(self):
        self.app.Quit()
        pythoncom.CoUninitialize()

    def open(self, path):
        self.app.Presentations.Open(path)

    def full_screen(self):
        if self.has_active_presentation():
            self.app.ActivePresentation.SlideShowSettings.Run()
            return self.get_active_presentation_slide_index()

    def click(self):
        win32api.keybd_event(VK_CODE['spacebar'], 0, 0, 0)
        win32api.keybd_event(VK_CODE['spacebar'], 0 , win32con.KEYEVENTF_KEYUP, 0)
        return self.get_active_presentation_slide_index()

    def goto_slide(self, index):
        if self.has_active_presentation():
            try:
                self.app.ActiveWindow.View.GotoSlide(index)
                return self.app.ActiveWindow.View.Slide.SlideIndex
            except Exception as e:
                self.app.SlideShowWindows(1).View.GotoSlide(index)
                return self.app.SlideShowWindows(1).View.CurrentShowPosition

    def next_page(self):
        if self.has_active_presentation():
            count = self.get_active_presentation_slide_count()
            index = self.get_active_presentation_slide_index()
            return index if index >= count else self.goto_slide(index+1)

    def pre_page(self):
        if self.has_active_presentation():
            index = self.get_active_presentation_slide_index()
            return index if index <= 1 else self.goto_slide(index-1)

    def get_active_presentation_slide_index(self):
        if self.has_active_presentation():
            try:
                index = self.app.ActiveWindow.View.Slide.SlideIndex
                return index
            except Exception as e:
                print(e)
                index = self.app.SlideShowWindows(1).View.CurrentShowPosition
                return index

    def get_active_presentation_slide_count(self):
        return self.app.ActivePresentation.Slides.Count

    def get_presentation_count(self):
        return self.app.Presentations.Count

    def has_active_presentation(self):
        return True if self.get_presentation_count() > 0 else False


if __name__ == '__main__':
    ppt = PPTControler()
    ppt.open(r'D:\Project\LLV\pptAgnet\ppt_test.pptx')
    time.sleep(2)
    ppt.full_screen()
    time.sleep(2)
    ppt.goto_slide(6)
    time.sleep(2)
    ppt.next_page()
    time.sleep(2)
    ppt.pre_page()
    time.sleep(2)