from flask import Flask, request, flash
from werkzeug.utils import secure_filename
from printer import Printer
import time
import os


class Web(object):
    """Web is the class that gets all of the information from web calls ( API and Web page ) and provides checks before sending stuff to printing"""

    def __init__(self, app, printer):
        super(Web).__init__()
        self.printer = printer
        self.app = app

    def print_sms(self, texte, sign: str) -> bool:
        """
        Get text and a signature, prints the text and cuts after that.
        """
        self.app.logger.debug("Printing : " + str(texte) + " from " + str(sign))
        try:
            self.printer.print_sms(texte, sign)
            self.printer.cut()
        except Exception as e:
            self.app.logger.error(e)
            raise RuntimeError("Could not print SMS, " + str(e)) from e

        return True

    def print_image(self, image, sign: str) -> bool:
        """
        Get an image and a signature, prints the image and cuts after that.
        """
        try:
            self.upload_file(image)
        except Exception as e:
            self.app.logger.error(e)
            raise RuntimeError("Could not upload file") from e

        self.app.logger.debug("File has been uploaded, printing...")


        try:
            self.printer.print_img(
                os.path.join(
                    self.app.config["UPLOAD_FOLDER"],
                    secure_filename(image.filename),
                ),
                sign=sign,
                process=True,
            )
            self.printer.cut()
        except Exception as e:
            raise RuntimeError("Could not print file") from e

        self.app.logger.debug("Image printed and cut !")
        return True

    def login(self, username: str, password: str) -> bool:
        """Not implemented"""
        return

    def logout(self, username: str, password: str) -> bool:
        """Not implemented"""
        return

    def allowed_file(self, filename) -> bool:
        self.app.logger.debug("Is the filename allowed ?")
        return (
            "." in filename
            and filename.rsplit(".", 1)[1].lower()
            in self.app.config["ALLOWED_EXTENSIONS"]
        )

    def upload_file(self, image) -> bool:
        self.app.logger.debug("Validating file")
        if image and self.allowed_file(image.filename):
            filename = secure_filename(image.filename)
            self.app.logger.debug("File valid")
            try:
                image.save(os.path.join(self.app.config["UPLOAD_FOLDER"], filename))
            except Exception as e:
                self.app.logger.error("Could not save file %s", e)
                return False

            self.app.logger.debug(
                "File saved to "
                + str(os.path.join(self.app.config["UPLOAD_FOLDER"], filename))
            )
            return True
        else:
            self.app.logger.error("Could not save file " + str(filename))
            return False
