from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import UniqueConstraint
import hashlib
import os

db = SQLAlchemy()


class Seller(UserMixin, db.Model):
    __tablename__ = 'sellers'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


class Purchase(db.Model):
    __tablename__ = 'purchases'

    id = db.Column(db.String(64), primary_key=True)
    seller_id = db.Column(db.Integer, db.ForeignKey('sellers.id'))
    total_numbers = db.Column(db.Integer, default=0)
    numbers_left = db.Column(db.Integer, default=0)
    remarks = db.Column(db.Text)

    def generate_id(self):
        self.id = hashlib.sha256(os.urandom(60)).hexdigest()

    def decrease_numbers(self):
        if self.numbers_left > 0:
            self.numbers_left -= 1
        else:
            raise Exception('No numbers left for this purchase')


class Raffle(db.Model):
    __tablename__ = 'raffles'

    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(128))


class Ticket(db.Model):
    __tablename__ = 'tickets'

    id = db.Column(db.Integer, primary_key=True)
    purchase_id = db.Column(db.String(64), db.ForeignKey('purchases.id'))
    raffle_id = db.Column(db.Integer, db.ForeignKey('raffles.id'))
    buyer_name = db.Column(db.String(64))
    buyer_contact = db.Column(db.String(64))
    chosen_number = db.Column(db.Integer)

    raffle = relationship(Raffle)

    __table_args__ = (
        UniqueConstraint('raffle_id', 'chosen_number', name='unique_raffle_number'),
    )
