from PIL import Image, ImageDraw, ImageFont

from oscar.apps.shipping.methods import Free
from decimal import Decimal as D
from apps.shipping.abstract_shipping import AbstractShipping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen import canvas
from hookcoffee.pdf_settings import *
import io
import img2pdf


class Singpost(Free, AbstractShipping):
    name = 'Singpost standard delivery'
    code = 'singpost'
    description = 'Singpost standard delivery 3-5 working days Tracking is not available. Direct to letter box'

    def process_shipment(self, order):
        return ''

    def get_waybill_pdf(self, waybill=None, order=None):
        # The data needed
        W, H = (1000, 600)
        font = ImageFont.truetype(IMAGE_FONTS['AMATIC_BOLD'], 80)
        image = Image.new('RGB', (W, H), (255, 255, 255))
        draw = ImageDraw.Draw(image)

        shipping_address = order.shipping_address
        # the line to draw
        text = "{}\n{}\n{}\n{}\n{}".format(
            shipping_address.name,
            shipping_address.line1,
            shipping_address.line2,
            shipping_address.country.name,
            shipping_address.postcode
        )
        # Draw on
        w, h = draw.multiline_textsize(text, font=font)
        draw.multiline_text(((W - w) / 2, (H - h) / 2), text, align='center', fill="black", font=font)

        # Write to byte stream
        img_bytes = io.BytesIO()
        image.save(img_bytes, 'jpeg')

        stream = io.BytesIO()
        img2pdf.convert(img_bytes.getvalue(), outputstream=stream)
        return stream.getvalue()

    def tracking_url(self):
        return 'No tracking available'

    def tracking_available(self):
        return False


__shipping_method_class__ = Singpost
