# -*- coding: utf-8 -*-
from django.db import models

from . import pricing


class Order(models.Model):
    """One order placed from the landing page order form.

    The customer-facing site is in Bangla; this admin side is in English.
    Only the labels are English — the stored values (product name, address,
    customer name) are whatever the shop and the customer actually wrote.
    """

    AREA_INSIDE = 'inside'
    AREA_OUTSIDE = 'outside'
    AREA_CHOICES = [
        (AREA_OUTSIDE, 'Outside Dhaka'),
        (AREA_INSIDE, 'Inside Dhaka'),
    ]

    STATUS_NEW = 'new'
    STATUS_CONFIRMED = 'confirmed'
    STATUS_SHIPPED = 'shipped'
    STATUS_DELIVERED = 'delivered'
    STATUS_CANCELLED = 'cancelled'
    STATUS_CHOICES = [
        (STATUS_NEW, 'New'),
        (STATUS_CONFIRMED, 'Confirmed'),
        (STATUS_SHIPPED, 'Shipped'),
        (STATUS_DELIVERED, 'Delivered'),
        (STATUS_CANCELLED, 'Cancelled'),
    ]

    order_no = models.CharField('Order number', max_length=20, unique=True,
                                blank=True, db_index=True)

    # ---------- customer ----------
    customer_name = models.CharField('Customer name', max_length=60)
    phone = models.CharField('Mobile number', max_length=20, db_index=True,
                             help_text='Stored as 8801XXXXXXXXX')
    phone_typed = models.CharField('Number as typed', max_length=25, blank=True)
    address = models.TextField('Address', max_length=300)
    country = models.CharField('Country', max_length=2, default='BD')

    COLOR_CHOICES = pricing.COLOR_CHOICES

    # ---------- product (static — same set on every order) ----------
    product_name = models.CharField('Product', max_length=120,
                                    default=pricing.PRODUCT_NAME)
    product_name_en = models.CharField('Product (English)', max_length=120,
                                       default=pricing.PRODUCT_NAME_EN, blank=True)
    product_sku = models.CharField('SKU / code', max_length=60,
                                   default=pricing.PRODUCT_SKU, blank=True)
    color = models.CharField('Colour', max_length=20, blank=True, db_index=True,
                             choices=pricing.COLOR_CHOICES,
                             help_text='Which colour the customer picked.')

    # ---------- money (always calculated on the server) ----------
    quantity = models.PositiveSmallIntegerField('Quantity', default=1)
    unit_price = models.PositiveIntegerField('Unit price (Tk)', default=0)
    subtotal = models.PositiveIntegerField('Subtotal (Tk)', default=0)
    delivery_area = models.CharField('Delivery area', max_length=10,
                                     choices=AREA_CHOICES, default=AREA_OUTSIDE)
    delivery_charge = models.PositiveIntegerField('Delivery charge (Tk)', default=0)
    total = models.PositiveIntegerField('Total (Tk)', default=0)

    # ---------- free gift ----------
    gift = models.CharField('Free gift', max_length=120, blank=True)
    gift_size = models.CharField('T-shirt size', max_length=10, blank=True)

    # ---------- shop-side bookkeeping ----------
    status = models.CharField('Status', max_length=12, choices=STATUS_CHOICES,
                              default=STATUS_NEW, db_index=True)
    admin_note = models.TextField('Your note', blank=True,
                                  help_text='Only you see this. The customer never does.')

    ip_address = models.GenericIPAddressField('IP address', null=True, blank=True)
    user_agent = models.CharField('Browser', max_length=300, blank=True)

    created_at = models.DateTimeField('Placed at', auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField('Last updated', auto_now=True)

    class Meta:
        verbose_name = 'Order'
        verbose_name_plural = 'Orders'
        ordering = ['-created_at']

    def __str__(self):
        return '%s — %s (%s)' % (self.order_no or self.pk, self.customer_name, self.phone)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if not self.order_no:
            # Needs the pk, so it is stamped right after the first INSERT.
            self.order_no = 'AR-%05d' % self.pk
            Order.objects.filter(pk=self.pk).update(order_no=self.order_no)

    @property
    def dialable_phone(self):
        """'+8801XXXXXXXXX' — ready for a tel: link in the admin."""
        digits = ''.join(c for c in self.phone if c.isdigit())
        return '+' + digits if digits else ''

    @property
    def color_label(self):
        """'Red' for the admin; '' when this product has no colours."""
        return dict(pricing.COLOR_CHOICES).get(self.color, self.color)

    @property
    def area_label(self):
        return dict(self.AREA_CHOICES).get(self.delivery_area, self.delivery_area)
