from typing import List, Optional

from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session

from app.crud.base import CRUDBase
from app.models.serial_number import SerialNumber
from app.schemas.serial_number import SerialNumberCreate, SerialNumberUpdate

from app.utils import random_name

class CRUDSerialNumber(CRUDBase[SerialNumber, SerialNumberCreate, SerialNumberUpdate]):
    
    def valid(self, db: Session, *, ser_no:str) -> Optional[SerialNumber]:
        return db.query(SerialNumber).filter(SerialNumber.code==ser_no).first()

    def available(self, db: Session, *, ser_no:str) -> Optional[SerialNumber]:
        valid_ser_no = self.valid(db, ser_no=ser_no)
        if valid_ser_no and not valid_ser_no.is_used:
            return valid_ser_no
        else:
            return None
        
    
serial_number = CRUDSerialNumber(SerialNumber)